Remove values from an array in Perl

Home > Search
  by

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

@fruits = qw(apple banana orange grapes);

 

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

# Count the number of values in the array
$count = scalar @fruits;

# Set the index to zero
$index = 0;

# Find every occurence of the value that you want to remove from the array
$index++ until $fruits[$index] eq 'grape' or $index == $count;

# Remove every occurence from the array
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 in the box below so that we can be sure you are a human.




Comments