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)},"
In reply to Re: evaluation strategy of perl
by Sidhekin
in thread evaluation strategy of perl
by mayaTheCat
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |