in reply to Regex variable capturing gotcha

Yes, it does.

$ perl -le'"foo" =~ /(foo)/; print $1; "bar" =~ /(bar)/; print $1;' foo bar

What you got wrong is that a failed match will not change the values:

$ perl -le'"foo" =~ /(foo)/; print $1; "bar" =~ /(bar)/; print $1; "ba +z" =~ /(quux)/; print $1;' foo bar bar

Of course then, if all you're matching for is /(foo)/, and you succeed on the very first match, $1 will never be anything other than foo. What you need to do is check whether your match succeeded:

while(<DATA>) { if( $_ =~ /(foo)/ ) { print "$.: $1 -- $&\n"; } else { print "No match on line $..\n" } }

This is documented behaviour.

As a sidenote, instead of keeping a line counter yourself, you can use Perl's $. variable, which contains the number of the last line read from the last accessed filehandle.

Makeshifts last the longest.

Replies are listed 'Best First'.
Re^2: Regex variable capturing gotcha
by Anonymous Monk on Aug 05, 2004 at 00:31 UTC
    As a sidenote, instead of keeping a line counter yourself, you can use Perl's $. variable,
    Good advice, but it looks like it's a match count, not a line count.