in reply to Re: evaluation strategy of perl
in thread evaluation strategy of perl

There is something significantly different between the two for styles in your last two examples.... Can you explain why $i binds early and $j binds late?
#!/usr/bin/perl -wT use strict; my (@d,$i,$j); # all vars in same scope for $i (1..3) { push @d, sub { print "$i\n" }; # same as line below } for ($j = 1; $j<=3; $j++) { push @d, sub { print "$j\n" }; # same as line above } $_->() for @d; # execute all anon subs __END__ 1 2 3 4 4 4

-Blake

Replies are listed 'Best First'.
Re^3: evaluation strategy of perl
by Aristotle (Chancellor) on Sep 20, 2002 at 15:33 UTC
    The for(LIST) doesn't bind early either. However, $i is just an alias to a different value, so rather than $i itself, the closure remembers the alias. It's easily visible if we use an array rather than a literal list.
    #!/usr/bin/perl -w use strict; my @t = (1,2,3); my @d; for my $i (@t) { push @d, sub { print "$i\n" }; } $_++ for @t; &$_ for @d; __END__ 2 3 4
    I hadn't thought about that, though in retrospect it's quite clear. Thanks for making me ponder this.

    Makeshifts last the longest.