hi monks, a while ago I tried to code something similar to the following one:

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


In reply to evaluation strategy of perl by mayaTheCat

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.