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


in reply to Re: Lexical closures
in thread Lexical closures

The "my $i" outside the loop does not declare a lexical variable that is used as the the loop variable in the way you think it does. Perl aliases the loop variable to each element in the for list as they are iterated over so the closure is not over $i, but over the aliased list elements. Consider:

use strict; use warnings; my @flist; my @array = 0 .. 3; for my $elt (@array) { push @flist, sub {return $elt;}; } print $_->(), "\n" for @flist; @array[0 .. 3] = 10 .. 13; print $_->(), "\n" for @flist;

Prints:

0 1 2 3 10 11 12 13

Perl reduces RSI - it saves typing