Christine Zhu
Christine Zhu

Reputation: 87

Perl Named Captured Group

I have created two named capture variables in the regex and the second one doesn't seem to return any value while the first one can. I am not sure why..here is the code.

my $string = 'test [google] another test [windows]';

my $regex=qr/\w*\[{1}(?<firstBracket>\w+)\]{1}(?<secondBracket>\w*)/ip;

$string=~ /$regex/;

say $+{secondBracket};

I am expecting that "secondBracket" will return. I can do $+{firstBracket}, but not the second one...Can someone help please?

Thanks.

Upvotes: 2

Views: 2442

Answers (1)

clt60
clt60

Reputation: 63892

You probably mean:

my $string = 'test [google] another test [windows]';

if( $string =~ /.*?\[(?<firstBracket>\w+)\].*?\[(?<secondBracket>\w+)\]/i ) {
        say $+{firstBracket};
        say $+{secondBracket};
}

output

google
windows

or

my $re = qr/.*?\[(?<firstBracket>\w+)\].*?\[(?<secondBracket>\w+)\]/i;
if( $string =~ $re ) {
    ...
}

with same output...

Upvotes: 6

Related Questions