|XP is just a number|
'Dynamic scoping' of capture variables ($1, $2, etc.)by AnomalousMonk (Chancellor)
|on Dec 16, 2012 at 20:03 UTC||Need Help??|
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
(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?