in reply to Localized Backreferences, If Statements & Blocks

Hmm, you get the results you expect if you place an extra pair of braces around the if construct.
#!/usr/bin/perl -w use strict; $|++; my $valid ='realgoodname'; my $invalid ='bad name'; my ($test1,$test2); { if ($valid =~ /^([a-z]+)$/i){ $test1=$1; } } { $invalid =~ /^([a-z]+)$/i; $test2=$1; die "Invalid test2" unless $test2; } print "Valid word\t= $valid\nInvalid word\t= $invalid\n\n"; print "Valid test\t= $test1\nInvalid test\t= $test2\n"; exit();
Apparently, stuff inside of the braces on an if statement is not localized. Therefore, the behaviour of $1 does not fit any of the conditions you specified from the Camel. I learn something new about Perl every day :)

Cheers,
Ovid

Update: Duh! The regex wasn't in the block. It's amazing how simple these things often turn out to be. Thanks, chromatic.

Join the Perlmonks Setiathome Group or just go the the link and check out our stats.

Replies are listed 'Best First'.
RE: (Ovid) Re: Localized Backreferences
by chromatic (Archbishop) on Sep 15, 2000 at 06:18 UTC
    It's not the scope of the if block that matters here, it's the scope of the regex. $1 is localized to the same scope. When you put the regex in that block, you enforced a more specific scope, and the behavior is more what you expect.

    Apparently, the interpreter doesn't treat a regex any differently if it's in an if statement or not -- consistency is good.

    In the original post, the regex was in package scope (not in an enclosing block). That means the end of the scope is the end of the file -- or the next successful backreference match which will assign something else to $1. Since the next regex doesn't match, and $1 is used before the end of the file, it still contains the last successful capture.

      Ahhhhhhhhh, I see the light.
      Thank you Brother...
RE (tilly) 2: Localized Backreferences
by tilly (Archbishop) on Sep 15, 2000 at 12:58 UTC
    Here is another new thing then. To quote Dan Sugalski about $1 etc in response to my claiming once that they were local:
    No they aren't. They're mutant pseudo-scalars attached to the underlying optree, and you may well get a $1 from the last time you matched that regex. (I've got a trivial program that shows the problem with a recursive call)
    (His "trivial program" causes threaded Perl to core-dump.)