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


in reply to Re^2: Lexical closures
in thread Lexical closures

Well, it depends on what the closures really close over, respectively when a new instance of the loop variable/value gets created. It seems that in Perl, at least when you use a lexical loop variable, you get a new copy each iteration, while in the other languages, you don't. To test this theory, create a new lexical variable within the loop body in each language and see if that's different, that is, use the local equivalent of the following Perl code to create the closures:

for (0..2) { my $i = $_; push @funcs, sub { $i * $_[0] }; };

You want to force allocation of a new instance of the lexical variable so your subroutine references get a new instance on each way around.

Of course, most of the languages have map, so using it would be more apt.