What, if any, are the benefits and dangers of using $_ within nested loops? For example:

my %cds = ( classical => [ [ 'Mozart', 'Requiem' ], [ 'Beethoven', '3rd Symphony' ] ], rock => [ [ 'Van Halen', '1984' ] ], jazz => [ [ 'Miles Davis', 'Birth of the Cool' ], [ 'Stan Getz', 'Brothers' ] ], ); for( sort keys %cds ) { print $_, ": ", scalar @{ $cds{$_} }, " in group\n"; for( @{ $cds{$_} } ) { print "\t", join(",", @{ $_ }), "\n"; } }

My question concerns using $_ in the inner loop of this example. Is is possible I'll destroy the value in $_ of the outer loop by creating the second for loop? Do I even need to worry about it, since I've already used the array reference in $_ by the time I enter the inner loop? Or is there a more evil threat that the inner loop itself will become corrupt?

# "for( ... ) { ... }" creates assignment to $_, right? # doesn't this 'corrupt' value for looking up $cds{$_} ? for( @{ $cds{$_} } ) { ... }

And if variable scoping would solve my percieved problem, understand that the issue of my vs. local is something I don't grok yet. I completely understand my, but local escapes me.

The odd thing is that I ran something like this, with -w and use strict;, and it worked! Why? Should it have worked?


In reply to Using $_ in nested loops by t'mo

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.