in reply to removing x from a list
my @array = (5, 4, 3, 2, 1); foreach (0 .. $#array) { print "$_ => $array[$_]\n"; if ($array[$_] <= 3) { print "Splicing $_ => $array[$_]\n"; splice @array, $_, 1; } }
What happens is that (0 .. $#array) is set to (0 .. 4) at the very beginning of the list. This means that you'll be trying to access an array subscript that doesn't exist if any of your splices actually occur.
This is actually one of the few places that a while loop is better than a foreach loop. Make the following change:
That works quite nicely.my @array = (5, 4, 3, 2, 1); my $i = 0; SPLICER: while ($i < @array) { print "$i => $array[$i]\n"; if ($array[$i] <= 3) { print "Splicing $i => $array[$i]\n"; splice @array, $i, 1; next SPLICER; } $i++; }
|
|---|