5

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)?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
David B
  • 29,258
  • 50
  • 133
  • 186
  • possible duplicate of [What is the best way to delete a value from an array in Perl?](http://stackoverflow.com/questions/174292/what-is-the-best-way-to-delete-a-value-from-an-array-in-perl) – Matthew Simoneau Apr 10 '14 at 20:53

2 Answers2

7

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.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
7

Your idea of using grep is good

@arr = grep { cond($i++); } @arr;
DVK
  • 126,886
  • 32
  • 213
  • 327