Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: evaluation strategy of perl

by Aristotle (Chancellor)
on Sep 20, 2002 at 14:34 UTC ( [id://199486]=note: print w/replies, xml ) Need Help??


in reply to evaluation strategy of perl

The problem is that interally, "$i\n" becomes $i . "\n" - which demonstrates why the problem occurs. You have to interpolate the value beforehand:
for (my $i = 0; $i<3; $i++) { my $str = "$i\n"; push @d, sub { print $str }; }
However, that will not work correctly:
0
1
2
Oops. You meant
for (my $i = 1; $i<=3; $i++) { my $str = "$i\n"; push @d, sub { print $str }; }
Because of this sort of problems, you should use the for(LIST) form.
for my $i (1..3) { my $str = "$i\n"; push @d, sub { print $str }; }
That eliminates an entire class of mistakes known as "fencepost errors", where the loop limit condition is fudged, usually resulting in one-off errors (one iteration too many or too few).

Makeshifts last the longest.

Replies are listed 'Best First'.
Re: Re: evaluation strategy of perl
by blakem (Monsignor) on Sep 20, 2002 at 15:15 UTC
    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

      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://199486]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-19 17:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found