http://www.perlmonks.org?node_id=833943


in reply to a sub within a sub -- revisiting

bar is still visible outside of foo, so make it lexical
sub foo { my $bar = sub { my ($i) = @_; push @arrb, $arra[$i]; }; $bar->($#arra); ... }

Replies are listed 'Best First'.
Re^2: a sub within a sub -- revisiting
by ikegami (Patriarch) on Apr 11, 2010 at 06:21 UTC

    Note that the above leaks if the anon sub accesses $bar. That would be the case if the anon sub is recursive, for example. I find the following simpler, and it doesn't leak.

    sub foo { ... local *bar = sub { ... }; bar(...); }