FreeKB - 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 value in the array has a unique index integer.

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


Splice can be used to add or remove any value in an array. To remove "orange", the second splice parameter must be the integer that correlates to the value you want to remove. In other words, specifying 2 removes orange.

splice (@fruits, 2, 1);


In a Perl script, you typically will not know the integers that correlate to the values. You could create a variable that contains a value of 0.

my $index = 0;


Count the number of lines in the array. In this example, $count will contain a value of 4.

my $count = @fruits;


Increment $index by 1 until a line in the @fruits array equals "grapes" or when $index equals $count.

++$index until $fruits[$index] eq "grapes" or $index eq $count;


Splice can be used to remove a value from the array. In this example, every occurence of "grapes" will be removed from @fruits.

splice (@fruits, $index, 1);


Be aware that if lines in the array contain double quotes, this probably will fail to work as expected, since the comparison is wrapped in double quotes, like this.

until $fruits[$index] eq "value"


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 b0835 in the box below so that we can be sure you are a human.