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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Lexical closures
by backstab (Novice) on Oct 25, 2008 at 11:08 UTC | |
by chromatic (Archbishop) on Oct 25, 2008 at 18:40 UTC | |
by backstab (Novice) on Oct 25, 2008 at 21:37 UTC | |
by ikegami (Patriarch) on Oct 25, 2008 at 22:33 UTC | |
by GrandFather (Saint) on Oct 25, 2008 at 19:48 UTC | |
by ig (Vicar) on Oct 26, 2008 at 01:37 UTC | |
by backstab (Novice) on Oct 25, 2008 at 20:45 UTC |