What is the scope of $1 through $9 in Perl? For instance, in this code:
sub bla {
my $x = shift;
$x =~ s/(\d*)/$1 $1/;
return $x;
}
my $y;
# some code that manipulates $y
$y =~ /(\w*)\s+(\w*)/;
my $z = &bla($2);
my $w = $1;
print "$1 $2\n";
What will $1 be? Will it be the first \w* from $x or the first \d* from the second \w* in $x?
from
perldoc perlreThis means that the first time you run a regex or substitution in a scope a new
localized copy is created. The original value is restored (à la local) when the scope ends. So,$1will be 10 up until the regex is run, 20 after the regex, and 10 again when the subroutine is finished.But I don’t use regex variables outside of substitutions. I find much clearer to say things like
where
$firstand$secondhave better names that describe their contents.