I suppose I knew that, although that didn't occur to me as an explanation.

I guess I'm trying to understand "how it works" on the inside so that I know what behaviour to expect. From what I understand, local ($_); is roughly equivalent to:

my $saved = $_; $_ = undef; ... $_ = $saved;
so foreach saved a pointer to the original $_, which contains 'Sample' as a result of s///. This I understand; it's why $alias1 is unaffected. Yet $alias0 is affected, and I'm not quite sure that I understand why. (This is no different than the local() case.)

Inside the foreach, we alias to $x. This doesn't affect the preexisting aliases, but on the next iteration through the loop our alias still exists. The behaviour changes if the line *_ = *x; is changed to *_ = \$x;, and this is what I was trying to understand.

Hmm, maybe I'm starting to get it now. *x is a 'level higher' than \$x in the internal structure of the symbol table. So foreach is only localizing the scalar (and restoring it at exit - this changes what $_ is after the loop if that change is made), and changes to the typeglob take foreach() completely unawares.

Update: It turns out what was confusing me was that foreach() apparently makes its own copy of the glob for *_, as the alias *_ = *x doesn't change where foreach() puts its alias. *_ = \$x leaves the glob alone, and just modifies the scalar portion; this does get overwritten by foreach()'s aliasing on each iteration (and at loop exit) provided the glob has not been changed.


In reply to Re^2: Understanding typeglobs and local() by whio
in thread Understanding typeglobs and local() by whio

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.