<?xml version="1.0" encoding="windows-1252"?>
<node id="1009374" title="Re^3: 'Dynamic scoping' of capture variables ($1, $2, etc.)" created="2012-12-18 09:22:57" updated="2012-12-18 09:22:57">
<type id="11">
note</type>
<author id="616540">
moritz</author>
<data>
<field name="doctext">
&lt;p&gt;It's a good guess, because there is a the fact that $1 points into the original string, and can change when the original string changes. But it's not the source of the confusion here.&lt;/p&gt;

&lt;p&gt;You can see that by changing the original code to use &lt;c&gt;m/(\d+)/g&lt;/c&gt; instead of &lt;c&gt;s/(\d+)//&lt;/c&gt;, thus not modifying the original string at all:

&lt;code&gt;
sub R {
   printf qq{before: \$_ is '$_'};
   printf qq{  \$1 is %s \n}, defined($1) ? qq{'$1'} : 'undefined';
   m/(\d+)/g ? $1 + R() : 0;
   printf qq{after: \$_ is '$_'};
   printf qq{ \$1 is %s \n}, defined($1) ? qq{'$1'} : 'undefined';
}
$_ = 'a81b2d34c1';
R();
__END__
before: $_ is 'a81b2d34c1'  $1 is undefined 
before: $_ is 'a81b2d34c1'  $1 is '81' 
before: $_ is 'a81b2d34c1'  $1 is '2' 
before: $_ is 'a81b2d34c1'  $1 is '34' 
before: $_ is 'a81b2d34c1'  $1 is '1' 
after: $_ is 'a81b2d34c1' $1 is '1' 
after: $_ is 'a81b2d34c1' $1 is '1' 
after: $_ is 'a81b2d34c1' $1 is '1' 
after: $_ is 'a81b2d34c1' $1 is '1' 
after: $_ is 'a81b2d34c1' $1 is '1' 
&lt;/code&gt;

&lt;p&gt;Let me repeat what I wrote earlier, but hopefully a bit clearer this time: &lt;b&gt;There is only one variable $1&lt;/b&gt;.  The first  call to m/()/ or s/()// creates the dynamic variable $1, and all subsequent calls &lt;b&gt;modify the existing variable $1&lt;/b&gt;. Since there is no mechanism for resetting $1 to a previous value, you can see the last value of $1 in all stack frames that have access to it.&lt;/p&gt;

&lt;!-- Node text goes above. Div tags should contain sig only --&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-616540"&gt;
[http://perl6.org/|Perl 6 - the future is here, just unevenly distributed]
&lt;/div&gt;&lt;/div&gt;</field>
<field name="root_node">
1009091</field>
<field name="parent_node">
1009352</field>
</data>
</node>
