bradcathey has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monasterians,

This one had me stumped! And while I did get it to work, I'm curious why this happens. Basically, the difference between the two examples is that the top one attempts to assign the backreference after the conditional block (returns undef) and the bottom one does it for each condition (and returns a value successfully). Question: why this behavior?

use strict; my $string = "This is a regex test"; my ($condition, $match); if ($condition) { $string =~ /(is a)/; } else { $string =~ /(regex)/; } $match = $1; print $match."\n";

And the winner:

if ($condition) { $string =~ /(is a)/; $match = $1; } else { $string =~ /(regex)/; $match = $1; } print $match."\n";

Thanks, all!

Update: Scooped by scope again! Thanks all, I knew there had to be an explanation somewhere, as the Camel was strangely silent on the topic.


—Brad
"Don't ever take a fence down until you know the reason it was put up." G. K. Chesterton

Replies are listed 'Best First'.
Re: Curious about regex capture in conditional
by davido (Cardinal) on Oct 20, 2004 at 18:09 UTC
    $<digits>
    Contains the subpattern from the corresponding set of capturing parentheses from the last pattern match, not counting patterns matched in nested blocks that have been exited already. (Mnemonic: like \digits.) These variables are all read-only and dynamically scoped to the current BLOCK.

    That's from perlvar, discussing the $1, $2, etc. special variables. You're just seeing evidence of the fact that those special variables are dynamically scoped to the current block. In your first test, the block ends before you get around to examining the contents of $1. When the block ends, the dynamic scope of $1 ends, and you can't see what used to be there.


    Dave

Re: Curious about regex capture in conditional
by blokhead (Monsignor) on Oct 20, 2004 at 18:09 UTC
Re: Curious about regex capture in conditional
by Limbic~Region (Chancellor) on Oct 20, 2004 at 18:58 UTC