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

I consider it a bad idea to define a named sub within another sub

I agree 100%. Anon subs are another story. For example, I use constructs such as

sub foo { my $shared_with_all_recur = ...; local *_recur = sub { ... _recur(...); ... }; _recur(...); }

Replies are listed 'Best First'.
Re^3: Defining a sub within a sub: OK?
by AnomalousMonk (Archbishop) on Oct 15, 2009 at 08:08 UTC
    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?

      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.