在Perl中删除数组元素的“正确”方法是什么?

时间:2020-12-05 21:22:38

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.

我有一个包含一组元素的数组。元素的顺序是无关紧要的 - 我使用数组,因为它是我在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)?

我知道splice()但我认为在迭代时使用它并不好。删除数组元素似乎已弃用。也许在@arr上使用grep(@arr = grep {...} @arr)?

What is the best practice here?

这里的最佳做法是什么?

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

也许使用哈希(虽然我真的不需要它)?

2 个解决方案

#1


7  

Your idea of using grep is good

你使用grep的想法很好

@arr = grep { cond($i++); } @arr;

#2


7  

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

根据文档,不推荐在数组值上调用delete,并且可能会在将来的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.

您可以在perldata中阅读有关切片的更多信息。

#1


7  

Your idea of using grep is good

你使用grep的想法很好

@arr = grep { cond($i++); } @arr;

#2


7  

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

根据文档,不推荐在数组值上调用delete,并且可能会在将来的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.

您可以在perldata中阅读有关切片的更多信息。