Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Re: evaluation strategy of perl

by blakem (Monsignor)
on Sep 20, 2002 at 15:15 UTC ( [id://199505]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (None)
    As of 2024-04-25 01:03 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found