Home > front end >  How to refer to the last capture group inside Perl code embedded in regex via (?{...})?
How to refer to the last capture group inside Perl code embedded in regex via (?{...})?

Time:01-20

I would like to be able to use the last capture group in the Perl code embedded via (?{...})

'foobar' =~ /(oo)(bar)(?{ $word = ${-1} })/

My attempt above fails. I want the variable $word to have the string bar after the regex.

CodePudding user response:

Do you want something like:

my $word = 'var';
my @match = 'foobar' =~ /(oo)(bar)/;
$word = $match[-1];
print $word, "\n";

Output:

bar

[EDIT]
By using the named captures, you can say:

my $word = "var";
'foobar' =~ /(?<g>oo)(?<g>bar)(?{$word=${$-{'g'}}[-1]})/;
print $word, "\n";
=> bar

If your perl version is 5.25 or newer, which supports the special variable @{^CAPTURE}, following code may work (not tested).

'foobar' =~ /(oo)(bar)(?{$word=${^CAPTURE}[-1]})/;

CodePudding user response:

Can also use the $ variable

The text matched by the highest used capture group of the last successful search pattern. It is logically equivalent to the highest numbered capture variable ($1, $2, ...) which has a defined value.

Example:

perl -wE'$v = shift // q(aabb); $v =~ /(a)(b)(?{ $m = $  })/; say $m'    #--> b
  •  Tags:  
  • Related