I'm not an expert on Tkx, but I think you might get bitten by the way closure variables are "shared".
Please compare
use strict; use warnings; # ---------- for each @list my @each; for my $i ( 1..3 ) { push @each, sub { warn "each: \t$i" }; } $_->() for @each; # ---------- for c-style my @cfor; for ( my $i = 1 ; $i < 4; $i++ ) { push @cfor, sub { warn "cfor: \t$i" }; } $_->() for @cfor; # ---------- generator sub gen { my ($x)=@_; return sub { warn "gen: \t$x" }; } my @gen; for ( my $i = 1 ; $i < 4; $i++ ) { push @gen, gen($i); } $_->() for @gen;
each: 1 at d:/exp/pm_closure.pl line 10. each: 2 at d:/exp/pm_closure.pl line 10. each: 3 at d:/exp/pm_closure.pl line 10. cfor: 4 at d:/exp/pm_closure.pl line 21. cfor: 4 at d:/exp/pm_closure.pl line 21. cfor: 4 at d:/exp/pm_closure.pl line 21. gen: 1 at d:/exp/pm_closure.pl line 31. gen: 2 at d:/exp/pm_closure.pl line 31. gen: 3 at d:/exp/pm_closure.pl line 31.
actually your case with a c-style loop is how it's supposed to be, your my $x has only one instance and only gets a new value with each iteration.²
for (@list)' is special because the loop var is an alias to the list-value. °
To avoid such confusions it's always safe to call a "generator" sub which returns a closure.
Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery
FootballPerl is like chess, only without the dice
°) the source of the famous "want stay shared" error. (UPDATE or because it's considered an inside declaration ?)
²) a c-style for is semantically just a while-loop with a prior declaration.
In reply to Re: Closure confusion in Tkx (declarations in loops)
by LanX
in thread Closure confusion in Tkx
by lbrandewie
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |