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_o
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
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
.
splice will remove array element(s) by index. Use grep, as in your example, to search and remove.
if you change
my @del_indexes = grep { $arr[$_] eq 'foo' } 0..$#arr;
to
my @del_indexes = reverse(grep { $arr[$_] eq 'foo' } 0..$#arr);
This avoids the array renumbering issue by removing elements from the back of the array first. Putting a splice() in a foreach loop cleans up @arr. Relatively simple and readable...
foreach $item (@del_indexes) {
splice (@arr,$item,1);
}
Is this something you are going to be doing a lot? If so, you may want to consider a different data structure. Grep is going to search the entire array every time and for a large array could be quite costly. If speed is an issue then you may want to consider using a Hash instead.
In your example, the key would be the number and the value would be the count of elements of that number.
I use:
delete $array[$index];
Perldoc delete.