in reply to Closure Confusion
I'll assume that you're actually returning @closures from make_closures(). Since you're reusing the same lexical $j within the loop, each closure encloses the same lexical. If you change the value in one, it'll change for all of the others.
The solution is to create a new lexical for each closure.
sub make_closures { my $j = 0; my @closures; while (++$j < 7) { my $value = $j; push (@closures, sub {print $value, "\n";}); } }
I also advise you not to use the &sub method of calling functions. It has implicit behavior that may not be what you want.
|
|---|