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

Aside from the fact that the approach given in your reply is 'cleaner' and therefore, to my mind, preferable to something like
sub foo { my $shared_with_all_recur = ...; my $_recur; $_recur = sub { ... $_recur->(...); ... }; $_recur->(...); }
is there any advantage to using a localized glob rather than a lexical scalar?

Replies are listed 'Best First'.
Re^4: Defining a sub within a sub: OK?
by ikegami (Patriarch) on Oct 15, 2009 at 12:49 UTC

    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.