What is the best way to delete a value from an array in Perl?

Tags: arrays perl
Question!

The array has lots of data and I need to delete two elements.

Below is the code snippet I am using,

my @array = (1,2,3,4,5,5,6,5,4,9);
my $element_omitted = 5;
@array = grep { $_ != $element_omitted } @array;
By : user21246


Answers

The best I found was a combination of "undef" and "grep":

foreach $index ( @list_of_indexes_to_be_skiped ) {
      undef($array[$index]);
}
@array = grep { defined($_) } @array;

That does the trick! Federico

By : Federico


You can use the non-capturing group and a pipe delim list of items to remove.


perl -le '@ar=(1 .. 20);@x=(8,10,3,17);$x=join("|",@x);@ar=grep{!/^(?:$x)$/o} @ar;print "@ar"'
By : Rich


Delete all occurrences of 'something' if array.

Based on SquareCog answer's:

my @arr = ('1','2','3','4','3','2', '3','4','3');
my @dix = grep { $arr[$_] eq '4' } 0..$#arr;
my $o = 0;
for (@dix) {
    splice(@arr, $_-$o, 1);
    $o++;
}
print join("\n", @arr);

Each time we remove index from @arr, the next correct index to delete will be $_-current_loop_step.

By : Tom Lime


This video can help you solving your question :)
By: admin