What is the difference between Perl regex variables $ {name} and $-{name} when both are used to refer to the same regex group from Perl statement/expression code?
CodePudding user response:
While $ {name} holds the captured substring referred by name
as a scalar value, $-{name} refers to an array which holds capture
groups with the name.
Here is a tiny example:
#!/usr/bin/perl
use strict;
use warnings;
'12' =~ /(?<foo>\d)(?<foo>\d)/; # '1' and '2' will be captured individually
print $ {'foo'}, "\n"; # prints '1'
for (@{$-{'foo'}}) { # $-{'foo'} is a reference to an array
print $_, "\n"; # prints '1' and '2'
}
As $ {name} can hold only a single scalar value, it is assigned
to the first (leftmost) element of the capture groups.
