AnomalousMonk has asked for the wisdom of the Perl Monks concerning the following question:
This question is prompted by the discussion of $1 not "freezing" in an addition.
perlre 5.14.2 (in the sub-section 'Capture groups') sez (emphases added):
Capture group contents are dynamically scoped and available to you
outside the pattern until the end of the enclosing block or until the
next successful match, whichever comes first. (See "Compound Statements"
in perlsyn.) You can refer to them by absolute number (using "$1" ...
(The reference in the quote above to the discussion in Compound Statements) does not seem to shed any light on the particular question of this post.
In the code example below, some dynamic scoping is clearly taking place since $1 begins and ends undefined. However, $1, set to '1' by the last successful match at the lowest-but-one level of recursion, is propagated upward unchanged through several levels of subroutine 'blocks' (as I understand them) until it exits the topmost. (local-izing $1 within the subroutine has no effect on this behavior.)
Might this behavior have something to do with the recursive nature of the subroutine: the compiler rewrites the recursive call as a branch to a point within the same block, and so $1 is only restored once because there is only one real block exit?
Can anyone throw any light on this? In particular, any links to documentation?
>perl -wMstrict -le "$_ = 'x55x666x7777x1x'; ;; print 'before: $1 is ', defined($1) ? qq{'$1'} : 'undefined'; print R(); print 'after: $1 is ', defined($1) ? qq{'$1'} : 'undefined'; ;; sub R { printf qq{ \$_ is '$_'}; printf qq{ \$1 is %s \n}, defined($1) ? qq{'$1'} : 'undefined'; return s/(\d+)// ? $1 + R() : 0; } " before: $1 is undefined $_ is 'x55x666x7777x1x' $1 is undefined $_ is 'xx666x7777x1x' $1 is '55' $_ is 'xxx7777x1x' $1 is '666' $_ is 'xxxx1x' $1 is '7777' $_ is 'xxxxx' $1 is '1' 4 after: $1 is undefined
Updates:
- Just in case the behavior above was an artifact of $1 being undefined initially, I tried setting $1 to a defined value via a successful match prior to the print $1/print R()/print $1 sequence. The result is no different: the value $1 starts out with at the 'top' level is the one it winds up with.
- I should mention I am running all my example code in this and other postings in this thread under Strawberry 5.14.2.1.
|
---|