t'mo has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Using $_ in nested loops
by merlyn (Sage) on Jan 12, 2001 at 10:38 UTC | |
|
Re: Using $_ in nested loops
by btrott (Parson) on Jan 12, 2001 at 10:42 UTC | |
|
Re: Using $_ in nested loops
by repson (Chaplain) on Jan 12, 2001 at 13:58 UTC | |
|
Re: Using $_ in nested loops
by a (Friar) on Jan 12, 2001 at 10:43 UTC | |
by t'mo (Pilgrim) on Jan 12, 2001 at 18:46 UTC |