in reply to Closure Confusion

Apart from that your sub make_closures doesn't return the array of closures so the code as supplied doesn't do anything , you have to realise that the reference to $j inside each of you generated closures is a reference to the $j in the sub make_closures(). Ie. They all refer to the same variable.

Here's a simple mod of your code that demonstrates the behavious that you were looking for... Maybe it will help clarify things.

#! perl -sw use strict; sub make_closures { my $j = 0; my @closures; while (++$j < 7) { my $jj = $j; push (@closures, sub {print $jj, "\n";}); } return @closures; } foreach my $sub (&make_closures) { $sub->(); } __DATA__ C:\test>205818 1 2 3 4 5 6

Here, I am creating a new var $jj inside the loop each time around and giving it the value, therefore each generated sub has its own independant variable/value, and the $j var gets garbage collected when it goes out of scope when make_closures() terminates.


Cor! Like yer ring! ... HALO dammit! ... 'Ave it yer way! Hal-lo, Mister la-de-da. ... Like yer ring!