Because $index is lexically scoped, it follows different rules than $_, which is dynamically scoped.

Each time you have a "my" variable declaration (a for-loop with a "my" variable essentially does this internally at the beginning of each iteration), it allocates a fresh memory location and binds it to the variable's name. Each pass through your loop, you create an anonymous sub that refers to the memory location of $index. But in each iteration, the name "$index" refers to a different memory location, so of your 11 different anonymous subs is pointing to a different memory location -- they don't interfere with each other... The name $index is bound to different memory locations depending on your lexical scope, so once you leave the scope where the anonymous sub was created, you can't change the value that the anonymous sub will see by changing what's in $index (well, without magic), because $index won't be pointing to the same memory location.

On the other hand, dynamic scoping works more like global variables. $_ is always bound to the same memory location, it doesn't matter what scope you are in. So when you create 11 different anonymous subs that use $_, they are all pointing to the same memory location. If some code in some other place changes $_ (a likely scenario), then these anonymous subs will use that new value as well.

blokhead


In reply to Re: Are we seeing syntax inconsistency? by blokhead
in thread Are we seeing syntax inconsistency? by TibetPerlMonk

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.