Hi

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

footnotes

°) 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.

updates
expanded example with clearer output and generator case

In reply to Re: Closure confusion in Tkx (declarations in loops) by LanX
in thread Closure confusion in Tkx by lbrandewie

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.