Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: anonymous vs named subroutines as closures

by ikegami (Pope)
on Jun 04, 2013 at 04:16 UTC ( #1036884=note: print w/replies, xml ) Need Help??


in reply to anonymous vs named subroutines as closures

Demonstration of "will not stay shared":

sub outer { my ($x) = @_; sub inner { say $x; } inner(); } # Warns Variable "$x" will not stay shared outer(4); # Prints 4 outer(6); # Prints 4!!!

Here's what's going on.

sub named { ... }

is more or less the same as

BEGIN { *named = sub { ... }; }

As such, it only captures once, when the sub is compiled.

In the above code, when outer goes out of scope, $x would normally be cleared. But since the closure still references it, a new $x is a created instead. From this point on, the $x in inner is different from the $x is outer; it "didn't stay shared".

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1036884]
help
Chatterbox?
[LanX]: B::Concise has an obvious bug in the example code ...
[LanX]: ... and I wouldn't be surprised if it hasn't been spoted for 10 years already
[LanX]: http://perldoc. perl.org/B/Concise .html#Example%3a- Altering-Concise- Renderings
[LanX]: :-/
[Corion]: Heh ;)
[Corion]: I might do a release of Filter::Simple, which has/"causes" bugs in line numbering, which also hasn't bothered too many people ;)

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (9)
As of 2017-04-24 15:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (442 votes). Check out past polls.