When the anon sub instance is created, it is associated with the variables that existed then.

When you use for my $x (or for my $_ in 5.10+), a new $x (or $_) is created for every pass of the loop. When the anon sub instance is created, it is associated with the iterator variable that existed then, a variable that was only used for that loop pass.

When you use for $_, for $_ or for $pkg, the loop simply reuses the existing variable. When the anon sub instance is created, it is associated with the iterator variable that existed then, a package variable whose value will change once the loop pass ends.

(Technically, package vars aren't captured at all. But unless you go mucking with the symbol table, the behaviour is the same as described.)

sub mk_pkg { for our $pkg (@_) { return sub { $pkg } } } sub mk_lex { for my $lex (@_) { return sub { $lex } } } our $pkg = "XXX"; print mk_pkg('abc')->(), "\n"; # XXX print mk_lex('abc')->(), "\n"; # abc

What was confusing me was why, in what seemed to be otherwise identical code, $a was capturing an alias inside the nested subroutine, but $_ was not.

$_ changed value. $a didn't. $a just became anonymous at the end of the loop pass.


In reply to Re: Too lazy to be lazy by ikegami
in thread Too lazy to be lazy by JadeNB

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.