in reply to Closure Confusion
sub make_closures { my $j = 0; my @closures; while (++$j < 7) { my $i = $j; push (@closures, sub {print $i;}); } return @closures; } foreach my $sub (&make_closures) { &$sub; }
This seems to work. I think the problem is that $j isn't going out of scope for each of the closures... so they're all pointing to the same address in memory, instead of to new addresses for each iteration.
But I really barely understand closures, so I may be way off base here.
-- Dan
PS - I couldn't get this to run from perl -e without adding the return statement. "Undefined subroutine &main:: called at -e line 13.". Am I missing something?
|
|---|