In most cases, splice is the simplest way of removing an item from the middle of an array but it is a dodgey practice to modify an array that you are iterating over using a for/foreach loop. Changing the array whilst you are halfway through it is not a good idea.
The easiest way to do what you want is to set the elements that are to be removed to undef in the loop and then use grep to remove them at the end.
#! perl -slw
use strict;
my @array = (1 .. 100);
print scalar @array;
for my $i (0 .. $#array) {
$array[$i] = undef if $array[$i] % 10 == 0;
}
print scalar @array;
@array = grep{ $_ } @array;
print scalar @array;
It is safe to remove elements from the top of the array whilst if you process the array in reverse order.
#! perl -slw
use strict;
my @array = (1 .. 100);
print scalar @array;
my @toDelete;
for my $i (reverse 0 .. $#array) {
splice(@array, $i, 1) if $array[$i] % 10 == 0;
}
print scalar @array;
You can also accumulate an array of indexes for the elements to be removed and use delete on an array slice built from the index array. Unfortunately, delete will only remove the element from the array completely of it happens to be the last element. Otherwise it just sets it to be undef and you still need to use grep to trim the rest out, so there is no advantage with this over the first method above.
Okay you lot, get your wings on the left, halos on the right. It's one size fits all, and "No!", you can't have a different color.
Pick up your cloud down the end and "Yes" if you get allocated a grey one they are a bit damp under foot, but someone has to get them.
Get used to the wings fast cos its an 8 hour day...unless the Govenor calls for a cyclone or hurricane, in which case 16 hour shifts are mandatory.
Just be grateful that you arrived just as the tornado season finished. Them buggers are real work. |