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


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

I understand your problem, for my understanding "dynamically scoped" should mean localized such that the sum at the end shouldn't be 4=1+1+1+1 but 1+7777+666+55.

but if you read the docs differently

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.

you can see that the next match within the recursion sets $1 to another value.

At least that's ATM my understanding of the designers intention.

> a branch to a point within the same block

no, no tail-head optimization in Perl!

I will try to run some experiments tomorrow.

UPDATE1:

hmm, w/o recursion and with different strings it works like localized:

DB<112> sub tst2 { 'a' =~ /(\w)/; $1. tst(). $1 } => 0 DB<113> sub tst { 'b' =~ /(\w)/; $1} => 0 DB<114> 'c' =~ /(\w)/; print $1. tst2(). $1 => 1 cabac

UPDATE2

you're right there is a bug in how recursive functions are handled:

DB<123> sub delchar { $x =~ s/(\w)// ? $1 . delchar() . $1 : "x" } => 0 DB<124> $x='abc' => "abc" DB<125> delchar() => "cccxccc"

in contrast explicitly different functions:

DB<138> sub del1 { $x =~ s/(\w)// ? $1 . del2() . $1 : "x" } => 0 DB<139> sub del2 { $x =~ s/(\w)// ? $1 . del3() . $1 : "x" } => 0 DB<140> sub del3 { $x =~ s/(\w)// ? $1 . del4() . $1 : "x" } => 0 DB<141> sub del4 { $x =~ s/(\w)// ? $1 . del5() . $1 : "x" } => 0 DB<142> $x='abc'; del1() => "abcxcba"

Perl 5.10

UPDATE3

the following shows that $1 is static per function, maybe they where implemented like closures.

DB<111> sub del2 { $x =~ s/(\w)// ? $1 . del1() . $1 : "-" } => 0 DB<112> sub del1 { $x =~ s/(\w)// ? $1 . del2() . $1 : "-" } => 0 DB<113> $x='abcd'; del1() => "cdcd-dcdc"

Cheers Rolf