I *had* a problem that I solved myself, namely that the hashrefs in @list had been replaced by scalars after the second for loop in the code below. I do perl for 6 years now but I still underestimate the globalness of $_ sometimes. My question is, is my intuition so far of the line, namely that $_ feels to me more block scoped, that I don't expect the "for @list" to replace the contents of @list because they are assigned to $_? Or did I forget to read some important documentation that should be read in the beginning. I did read almost the complete Camel Book (version 2).

Here's a simplified version of the code. The work_ sub was far away in a module and difficult to find then.

Hoping for some enlightenment on the nature of $_ ...

my @list = ( { a => 1 }, { a => 15 } ); # here the values of a in the hashrefs are changed, ok! work_( $_ ) for @list; print "_=".(ref $_ ? "r.$_->{a}" : $_) . "\n" for @list; # but here the hashrefs in @list are replaced by scalars, # namely the result of the work_() call. work_( $_, 1 ) for @list; print "_=".(ref $_ ? "r.$_->{a}" : $_) . "\n" for @list; sub work_ { my ($obj, $act) = @_; $obj->{a}++; $_ = $obj->{a} if $act; }

In reply to global $_ behavior by verdemar

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.