Bootstrap FreeKB - Perl (Scripting) - Remove element from array (splice)
Perl (Scripting) - Remove element from array (splice)

Updated:   |  Perl (Scripting) articles

Let's say you have an array of fruit that contains apple, banana, orange, and grape.

my @fruits = qw(apple banana orange grapes);

 

Each element in the array has a unique index number.

  • $fruits[0] = apple
  • $fruits[1] = banana
  • $fruits[2] = orange
  • $fruits[3] = grapes

Here is how you can loop through the items in the @fruits array and get the index number of each item.

foreach my $item (@fruits) {
  my ($index) = grep { $fruits[$_] eq $item } (0 .. @fruits - 1);
  print "$item index = $index \n";
}

 

Which should return the following.

apple index = 0 
banana index = 1 
orange index = 2 
grapes index = 3

 


Remove element from array using splice

Splice can be used to add or remove any element in an array.

  • The second parameter is the index number that correlates to the element you want to remove. In this example, index 2 is orange.
  • The thrid parameter is length. In other words, to remove orange and only orange, length must be 1.

Thus, the following would remove orange from the array.

splice (@fruits, 2, 1);

 

Often, the elements in an array are dynamic, thus you usually wouldn't want to hard code in the index number. Instead, the following can be used to get the index number of a specific element in the array.

my ($index) = grep { $fruits[$_] eq "orange" } (0 .. @fruits - 1);

 

In this example, $index will contain a value of 2, thus the following can be done to remove orange.

splice (@fruits, $index, 1);

 


Remove element from array using splice in a foreach loop

A loop can present a challenge. Let's say you have an array named @indexes_to_remove which contains 0 and 2.

my @indexes_to_remove = qw(0 2);

 

The goal being to remove item 0 (apple) and item 2 (orange).

apple index = 0 
banana index = 1 
orange index = 2 
grapes index = 3

 

If you were to try the following, the intial loop with item 0 would successfully remove item 0 (apple) from the array.

foreach my $index_number (@indexes_to_remove) {
  splice(@fruits, $index_number, 1);
}

 

However, once the initial loop has completed, then the @fruits array would look like this, thus the second loop with item 2 would remove grapes instead of orange.

banana index = 0
orange index = 1 
grapes index = 2

 

The following subroutine can be used to properly remove items from an array.

splice_indexes_from_array(\@fruits , @indexes_to_remove);

sub splice_indexes_from_array {
  my $array = shift @_;
  my $count = 0;

  foreach my $item (@_) {
    my $index = $item - $count;
    splice @{$array}, $index, 1;
    $count++;
  }

  return $array;
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 39a55a in the box below so that we can be sure you are a human.