Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: evaluation strategy of perl

by Sidhekin (Priest)
on Sep 20, 2002 at 14:35 UTC ( [id://199488]=note: print w/replies, xml ) Need Help??


in reply to evaluation strategy of perl

Making a subroutine, if you want it to use values rather than variables, the way to do it is string eval. ("evaluation strategy", indeed.)

use warnings; use strict; my @d; for (my $i = 0; $i<3; $i++) { push @d, eval qq/sub { print "$i\n" }/; } &{$d[0]}(); &{$d[1]}(); &{$d[2]}();

However, you will note that since the value of $i through this loop was 0, 1, and 2, that's what you get in output as well ... not 1, 2, and 3 :-)

Alternatively, you can choose to use variables, but then you need three variables. The above code makes only one. The below code uses three variables (all with the same name), and also prints 0, 1, and 2:

use warnings; use strict; my @d; for (my $i = 0; $i<3; $i++) { my $closure_var = $i; push @d, sub { print "$closure_var\n" }; } &{$d[0]}(); &{$d[1]}(); &{$d[2]}();

The Sidhekin
print "Just another Perl ${\(trickster and hacker)},"

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (2)
As of 2024-04-19 22:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found