in reply to The error says the value is uninitialized, but it works anyway
each HASH
each ARRAY
When called on a hash in list context, returns a 2-element list
consisting of the key and value for the next element of a hash. In
Perl 5.12 and later only, it will also return the index and value
for the next element of an array so that you can iterate over it;
older Perls consider this a syntax error. When called in scalar
context, returns only the key (not the value) in a hash, or the
index in an array.
So, using each, your code can go from:
to:$ perl -e ' my @colors = qw(red green blue yellow pink purple brown); my $count = @colors; my @drop = qw(pink brown); my $num = 0; foreach $num (1..$count){ $num--; if ($colors[$num] eq $drop[0] or $colors[$num] eq $drop[1]){ splice (@colors, $num, 1); } } print "@colors \n"; '
both produce the following output:$ perl -e ' my @colors = qw(red green blue yellow pink purple brown); my @drop = qw(pink brown); while ( my ($num, $val) = each @colors ) { if ($val eq $drop[0] or $val eq $drop[1]) { splice (@colors, $num, 1); } } print "@colors \n"; '
__output__ red green blue yellow purple
I hope that was the correct answer! :)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: The error says the value is uninitialized, but it works anyway
by AnomalousMonk (Archbishop) on Aug 18, 2019 at 06:34 UTC | |
by dbuckhal (Chaplain) on Aug 18, 2019 at 13:23 UTC |