Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^3: 'Dynamic scoping' of capture variables ($1, $2, etc.)

by LanX (Canon)
on Dec 16, 2012 at 22:48 UTC ( #1009098=note: print w/ replies, xml ) Need Help??


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

You are right be worried, your example code is just a bit to complex to make it evident at first glance.

There is no logical reason why nested calls of the same function (i.e. recursions) should act differently to nested calls of different functions.

see updated code, especially the second paragraph contrasting the bug.

Cheers Rolf

UPDATE:

to be sure to avoid any side effects from eval within the debugger here a standalone file for testing:

use warnings; use strict; use 5.10.0; my $x; sub delchar { $x =~ s/(\w)// ? $1 . delchar() . $1 : "x" } $x='abc'; say delchar(); # => "cccxccc" sub del1 { $x =~ s/(\w)// ? $1 . del2() . $1 : "x" } sub del2 { $x =~ s/(\w)// ? $1 . del3() . $1 : "x" } sub del3 { $x =~ s/(\w)// ? $1 . del4() . $1 : "x" } sub del4 { $x =~ s/(\w)// ? $1 . del5() . $1 : "x" } $x='abc'; say del1(); # => "abcxcba"

UPDATE:

Best practice is to copy captures like $1 ASAP! (not only in recursions)

DB<105> sub delchar { my $m; $m = $1 if $x =~ s/(\w)//; $m ? $m . +delchar() . $m : "-" } => 0 DB<106> $x='abc'; delchar() => "abc-cba" DB<107> sub delchar { local $m; $m = $1 if $x =~ s/(\w)//; $m ? $m + . delchar() . $m : "-" } => 0 DB<108> $x='abc'; delchar() => "abc-cba"


Comment on Re^3: 'Dynamic scoping' of capture variables ($1, $2, etc.)
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1009098]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (9)
As of 2014-08-29 21:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (289 votes), past polls