Your problem can be demonstrated by following simple code:

my @subs; for(my $i=1;$i<=5;$i++){ push @subs, sub { print "i=$i\n"; }; } $subs[3]->();

Inside the sub, $i is evaluated at the time the sub is called in the context/scope of the for-loop which has now terminated, so $i=5+1=6, which is the expected behaviour.

A workaround would be to create a sub via eval which will force it to consider $i's value at the time of the eval. But I am not sure if this is an elegant solution:

my @subs; for(my $i=1;$i<=5;$i++){ push @subs, eval <<EOE; sub { print "i=$i\n"; }; EOE } $subs[3]->();

btw, once you sort this out, you should start using arrays instead of ${"xx$i"}!

Update: another solution would be to introduce another variable local to the loop scope and use that:

my @subs; for(my $i=1;$i<=5;$i++){ my $j = $i; push @subs, sub { print "i=$i, j=$j\n"; }; } $subs[3]->();

Question: what's the difference between $i and $j, don't they both have the same scope?

bw, bliako


In reply to Re: Strange behavior of iteration while creating Perl/Tk widgets dynamically by bliako
in thread Strange behavior of iteration while creating Perl/Tk widgets dynamically by Vasek

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.