FreeKB - Remove values from an array in Perl
Remove values from an array in Perl

Home > Search


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

@fruits = qw(apple banana orange grapes);

 

You could create a variable that contains a value of 0.

my $index = 0;

 

Then, you could count the number of lines in the @fruits array. In this example, $count will contain a value of 4.

my $count = scalar @fruits;

 

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




Comments