I’ve just today discovered that, inside a regex, $_ takes on the value of the string being matched against:
16:12 >perl -wE "my $string = 'abcde'; $_ = 42; say; $string =~ /(?{ s +ay })/;" 42 abcde 16:12 >perl -v This is perl 5, version 22, subversion 0 (v5.22.0) built for MSWin32-x +64-multi-thread
This brings up two questions. First, is it documented anywhere? It’s not mentioned in the perlvar entry for $ARG.
Second, what is the rationale for this behaviour?
Here’s the background:
Following on from the recent thread Shorthand for /^\s*abc\s*$/ ?, I was experimenting with (??{ }) as an alternative means of parameterizing a regex without using a sub. This works:
use strict; use warnings; my %searches = ( bar => " bar \n\n", bar1 => " bar1 \nw\n", baz => "baz", foo => " foo c \n", foo1 => " foo ", ); my $x; my $regex = qr{ ^ \s* (??{ $x }) \s* $ }x; for (sort keys %searches) { $x = $_; print "$_: ", $searches{$_} =~ $regex ? 'match' : 'no match', "\n" +; }
but the use of $x is clumsy. So I tried $_ instead:
my $regex = qr{ ^ \s* (??{ $_ }) \s* $ }x;
After some debugging using perl -Mre=debug ..., it finally dawned on me that within the regex, $_ no longer contains the current hash key, but has been reset to the current hash value (i.e., the string on the left of the =~) with whitespace removed.1
Which seems strange to me, as well as unnecessary. Is there a situation in which this implicit assignment is actually useful?
1Update: Sorry, it’s (??{ $_ }) that has whitespace removed, due to the /x modifier.
Thanks,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Value of $_ inside a regex by Athanasius
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |