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'',@_};