Pathologically Eclectic Rubbish Lister PerlMonks

### Re: 'Dynamic scoping' of capture variables (\$1, \$2, etc.) (localization of captures in recursions is buggy!)

by LanX (Bishop)
 on Dec 16, 2012 at 21:03 UTC ( #1009094=note: print w/replies, xml ) Need Help??

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

• Comment on Re: 'Dynamic scoping' of capture variables (\$1, \$2, etc.) (localization of captures in recursions is buggy!)

Create A New User
Node Status?
node history
Node Type: note [id://1009094]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2018-04-22 01:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (82 votes). Check out past polls.

Notices?