Regex resetting the capture buffer

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Here's an example script:

 my $a = '1 foo';
 my $b = 'foo bar';

    if ( $a =~ /^\d+\s*(\w+)/ )    # line 1
        $b =~ s/bar/$1/;    # line 2
 print $b, "\n";

I am using the capture buffer in line 1 in the regex in line 2. But it
work. The capture buffer is cleared before the $1 substitution can take

I would have thought that Perl would perform the $1 substitution in the line
before it "recognizes" the substitution command and clears the capture

Please explain the order in which Perl processes line 1.

Do I have to "eval" line 2 to get it to work the way that I want without
to assign $1 to a temp var?



Re: Regex resetting the capture buffer

On 06/21/2007 10:34 AM, Mario D'Alessio wrote:
Quoted text here. Click to load it

Line 1 is not the issue, and it works as you expect it. Line 2 is the
problem; when a successful match occurs, the match variables are
set/reset to new values.

Quoted text here. Click to load it

Using eval() is worse than just assigning to a temporary variable.

Site Timeline