Use splicing if you already know the index of the item you want to remove.
Grep works if you are looking.
If you need to do a lot of them, you will get much better performance if you save your array in sorted order, since after that you can perform a binary search to find the index you need.
If this makes sense in your context, you might want to use the "magic value" for deleted records, rather than deleting them to preserve when moving data - for example, set deleted items to undef. Naturally, this has its own problems (if you need to know the number of "live" elements, you need to track them separately, etc.), But it may be a problem depending on your application.
Edit In fact, now when I take a second look - do not use the grep code above. It would be more convenient to find the index of the element you want to remove, and then use splicing to remove it (the code on which you accumulated all the inappropriate results.)
my $index = 0; $index++ until $arr[$index] eq 'foo'; splice(@arr, $index, 1);
This will remove the first occurrence. Removing all occurrences is very similar, except that you want to get all indexes in one pass:
my @del_indexes = grep { $arr[$_] eq 'foo' } 0..$#arr;
The rest remains as an exercise for the reader - remember that the array changes as it splices!
Edit2 John Syracuse correctly indicated that I had a mistake in my example .. fixed, sorry.
SquareCog Oct 06 '08 at 13:37 2008-10-06 13:37
source share