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

The perl foreach (or its alias for) loop does not have this problem.
my @subs; #for(my $i=1;$i<=5;$i++){ for my $i (1..5) { push @subs, sub { print "i=$i\n"; }; } $subs[3]->();

OUTPUT:

i=4
Bill

Replies are listed 'Best First'.
Re^3: Strange behavior of iteration while creating Perl/Tk widgets dynamically
by bliako (Abbot) on Oct 29, 2021 at 17:01 UTC

    And this code confirms your finding:

    my @subs; for(my $i=1;$i<=2;$i++){ print \$i."\n" } print "----\n"; for my $i (1..2) { print \$i."\n" }

    OUTPUT:

    SCALAR(0x55a429b66a28) SCALAR(0x55a429b66a28) ---- SCALAR(0x56399466d4d8) SCALAR(0x5639946924a0)

    Which made me try this:

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

    It prints i=100

    bw, bliako