Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^2: Strange behavior of iteration while creating Perl/Tk widgets dynamically

by BillKSmith (Monsignor)
on Oct 29, 2021 at 14:34 UTC ( #11138216=note: print w/replies, xml ) Need Help??


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 (Monsignor) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11138216]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2022-01-26 23:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (70 votes). Check out past polls.

    Notices?