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.
|
|---|