FreeKB - Perl Remove values from array (splice)
Perl - Remove values from array (splice)

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

 

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

  • The second parameter is the integer that correlates to the element you want to remove. In this example, integer 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);
$index = defined $index ? $index : -1;

 

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

splice (@fruits, $index, 1);

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |