style-light-choice
style-dark-choice 
Avatar
Gary
Vollink.com

Perl Match Vars Do Not Always Reset

I've been writing Perl for over 10 years, and I've never been bitten by this feature before this week. So, I'm sharing. Maybe it'll help, maybe you'll find it funny.
my $str = 'A MATCH';
$str =~ m/A (.*)$/;
print ": $1\n";  # Prints : MATCH

$str =~ m/z (.*)$/;
print ": $1\n";  # Prints : MATCH $1 did not reset

In the above $str does not match z, which means that the match itself did not succeed. Because the match does not succeed, $1 is still set from the previous match.

Normally, the success of the match itself should be tested with an if statement. I'm pretty sure that is why I've never noticed this issue.

The other fix is pretty simple. Write a match that will always work, it doesn't even have to set a capture, or do anything.

    my $str = 'A MATCH';
    $str =~ m/A (.*)$/;
    print ": $1\n";  # Prints : MATCH

"_" =~ m/_/;    # Reset $1 through $9


    $str =~ m/z (.*)$/;
    print ": $1\n";  # Prints : 

That's it. Simple thing. It was causing me a minor error in an unimportant place, but I was determined to find and fix it.

Valid CSS!