What you are observing is exactly what dynamic scoping is about: Code called from where the variable is defined can see it, even though it's not in the same lexical scope.
This can be demonstrated without recursion:
use 5.010;
use strict;
use warnings;
sub sayit {
say $1 // 'undef';
}
do {
'42' =~ /(\d+)/ and sayit();
};
sayit();
__END__
42
undef
Subroutine sayit reads $1 outside of the lexical scope of the block where $1 is set. But since it's in the dynamic scope, it can still see the value.
The sayit call outside the block prints undef\n, which demonstrates that $1 isn't merely a global variable.
As to your actual question:
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'
I see no evidence for that. After $1 is set to '1', exactly one more recursive call happens, and there it is printed out. Then the recursion ends, and you don't print $1 anymore.
Update: after experimenting a bit, I can provide evidence of the phenomen you mentioned:
sub R {
printf qq{before: \$_ is '$_'};
printf qq{ \$1 is %s \n}, defined($1) ? qq{'$1'} : 'undefined';
s/(\d+)// ? $1 + R() : 0;
printf qq{after: \$_ is '$_'};
printf qq{ \$1 is %s \n}, defined($1) ? qq{'$1'} : 'undefined';
}
$_ = 'x55x666x7777x1x';
R();
__END__
before: $_ is 'x55x666x7777x1x' $1 is undefined
before: $_ is 'xx666x7777x1x' $1 is '55'
before: $_ is 'xxx7777x1x' $1 is '666'
before: $_ is 'xxxx1x' $1 is '7777'
before: $_ is 'xxxxx' $1 is '1'
after: $_ is 'xxxxx' $1 is '1'
after: $_ is 'xxxxx' $1 is '1'
after: $_ is 'xxxxx' $1 is '1'
after: $_ is 'xxxxx' $1 is '1'
after: $_ is 'xxxxx' $1 is '1'
This is because there is only one variable $1. It is dynamically scoped, so once it is set in an inner scope, an outer scope sees the modification too.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|