mayaTheCat has asked for the wisdom of the Perl Monks concerning the following question:
use warnings; use strict; my @d; for (my $i = 0; $i<3; $i++) { push @d, sub { print "$i\n" }; } &{$d[0]}(); &{$d[1]}(); &{$d[2]}();
what I expected as the result of this script was
1
2
3
however, what I got was
3
3
3
so, I concluded that perl uses a "lazy evaluation" strategy, which means that it does not assign the value of a variable until the value is really needed.
for example, in my sample code the variable $i has the value 3 at time the three functions are called.
however, knowing the reason cannot solve my problem. is there a way to force perl to assign the value of the variable at the time the function is defined?
---------------------------------
life is ...
$mutation=sub{@_=split'';$gene=int(rand($#_+$=/$=));$_[$gene]=$=/$=-$_[$gene];$_=join'',@_};
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: evaluation strategy of perl
by dreadpiratepeter (Priest) on Sep 20, 2002 at 14:27 UTC | |
|
Re: evaluation strategy of perl
by kabel (Chaplain) on Sep 20, 2002 at 14:14 UTC | |
|
Re: evaluation strategy of perl
by Aristotle (Chancellor) on Sep 20, 2002 at 14:34 UTC | |
by blakem (Monsignor) on Sep 20, 2002 at 15:15 UTC | |
by Aristotle (Chancellor) on Sep 20, 2002 at 15:33 UTC | |
|
Re: evaluation strategy of perl
by Sidhekin (Priest) on Sep 20, 2002 at 14:35 UTC |