http://www.perlmonks.org?node_id=1009092


in reply to 'Dynamic scoping' of capture variables ($1, $2, etc.)

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.