Keep It Simple, Stupid | |
PerlMonks |
Localized Backreferences, If Statements & Blocksby doran (Deacon) |
on Sep 15, 2000 at 03:50 UTC ( [id://32591]=perlquestion: print w/replies, xml ) | Need Help?? |
doran has asked for the wisdom of the Perl Monks concerning the following question:
I had (apparently mistakenly) thought that a backreference to a parenthesized substring in a regexp would be undefined or at least equal to '' if it didn't match, so that in:
$test2 would always be left without a value (causing the script would die in this case). I certainly thought this given the $test1=$1; line was in a block after that if statement. Plus I created another block by throwing that pair of braces around the taint-checking/untainting of $invalid and $test2. This feeling was re-enforced when I checked the Camel book which sez: "The variables $1, $2, $3, ... are automatically localized, and their scope...extends to the end of the enclosing block or eval string, or to the next successfull pattern match, whichever comes first." Because of this I felt relatively safe in throwing a pair of braces around these tests, thinking that the backreference would never escape my enclosing block. However, it seems that the block after the if statement isn't enough. In the above example, $test2 is left with 'realgoodname' as a value. If I throw another block around the if statement, it seems to fix it. I guess my question is: How is it that $1 (in this case) can still be 'seen' outside of it's enclosing block? True, the second pattern match wasn't successful, but I sure thought that closing brace after the if statement would have prevented the previous value of $1 from carrying over to the next use of $1. If this is clearly documented someplace, feel free to point me in the correct direction. -Thanks
Back to
Seekers of Perl Wisdom
|
|