Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the 'right' way of deleting array elements in Perl?

Tags:

arrays

perl

I have an array containing a set of elements. The order of elements is irrelevant - I use an array since it's the simplest data structure I know in Perl.

my @arr = ...
while (some condition) {
    # iterate over @arr and remove all elements which meet some criteria
    # (which depends on $i)
}

I know of splice() but I think it's not good using it while iterating. delete for array elements seems deprecated. Perhaps use grep on @arr into itself (@arr = grep {...} @arr)?

What is the best practice here?

Perhaps use a hash (although I don't really need it)?

like image 256
David B Avatar asked Nov 24 '10 14:11

David B


People also ask

How do you remove an element from an array in Perl?

In Perl, the splice() function is used to remove and return a certain number of elements from an array. A list of elements can be inserted in place of the removed elements.

How do you remove elements from an array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.

How do you remove an array from an array?

You can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically.


2 Answers

Your idea of using grep is good

@arr = grep { cond($i++); } @arr;
like image 137
DVK Avatar answered Oct 02 '22 19:10

DVK


According to the docs, calling delete on array values is deprecated and likely to be removed in a future version of Perl.

Alternatively, you can build a list of needed indices and assign the slice to the original array:

@arr = @arr[ @indices ];

You can read more about slices in perldata.

like image 41
Eugene Yarmash Avatar answered Oct 02 '22 19:10

Eugene Yarmash