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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.