Perl: remove element from a list/array

You can easily push an element to a list/array, but when it comes to deleting an element, unless you know exactly its index number (which is rarely a case, as far as I’m concerned), things get unreasonably complicated.

I googled around and talked to people on IRC here’s what seems to be the best approaches:

  1. use splice in a loop with a counter
  2. use List::UtilsBy qw ( extract_by );

splice(); proved to be a really hard case. The following code will only remove 1st occurence in an array and ignore the rest, due to the fact that splice causes elements in a list to update their index numbers, so they get essentially offset and the counter is never adjusted for this fact (because I’m too lazy to figure out how). This code will do the job,  if your list contains unique elements  only, though.


use strict;
use warnings;

my @arr = (1, 2, 3, 4, “abc”, “zxy”, “qwerty”, “abcdef”);

my $index = 0;

foreach (@arr) {
if ($_ =~ m/abc.*/i) {
splice (@arr, $index, 1)
} else { $index++ }

If you print @arr to stdout you’ll see that abcdef is still there.

By and large, it’s a bad idea to modify an array in a for loop. If you one of a pretty, intuitive way to write a code that removes elements from an array do let me know, please.

extract_by looks like a real deal, but I abandoned it before I started really using it because I’ve realized that my code didn’t actually need to delete any elements from a list at all lol