I guess we have all been there: You make an "obviously trivial" change ... and the code fails to behave. This is a stripped down version of the "good" code:

use 5.030; use warnings; my @subrefs = (); for my $i (1..3) { push @subrefs, sub { print $i; }; } for (@subrefs) { $_->(); }

This prints 123, as I would expect.

The "trivial" change:

use 5.030; use warnings; my @subrefs = (); my $i = 0; for (1..3) { $i++; push @subrefs, sub { print $i; }; } for (@subrefs) { $_->(); }

This prints 333. WTF?

It seems the anonymous subroutine is not built with the value of $i, but with a reference to $i. I would not have expected this. Is this a bug, a quirk, or something which can be found documented somewhere?

Edited to add:

I wrote that bad code BC (Before Coffee), remembering that I had done something very similar before. I have now dug that up:

use 5.030; use warnings; my @subrefs; my $i = 0; for (1..3) { push @subrefs, sub { print ++$i }; } for (@subrefs) { $_->(); }

This prints 123. The difference is that the increment is done when the subroutine is called, not when the subs are declared and pushed to the array. In BC state I failed to see that difference.


In reply to Closures and scope of lexicals by haj

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.