Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^4: Defining a sub within a sub: OK?

by ikegami (Patriarch)
on Oct 15, 2009 at 12:49 UTC ( [id://801345]=note: print w/replies, xml ) Need Help??


in reply to Re^3: Defining a sub within a sub: OK?
in thread Defining a sub within a sub: OK?

It leaks memory.

use Devel::Peek; sub foo { my $_recur; $_recur = sub { $_recur->(); }; my $x; Dump($x); Dump($_recur,0); } foo();
SV = NULL(0x0) at 0x182a4d4 REFCNT = 1 FLAGS = (PADMY) SV = RV(0x182a1e0) at 0x182a1d4 REFCNT = 2 FLAGS = (PADMY,ROK) RV = 0x2381a4

Compare the refcount of $x (which will get freed) to $_recur's (which won't).

The problem is that the sub referenced by $_recur captures $_recur, and thus you have a memory loop. If you wanted a lexical, you would need to use

sub foo { my $shared_with_all_recur = ...; my $_recur; $_recur = sub { ... $_recur->(...); ... }; $_recur->(...); undef $_recur; }

This is a lot messier.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-04-18 18:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found