我有一些看起来像这样的Perl代码:
my @array = map { rand } ( 1..100 ); my @matching = grep { $_ == $condition } @array; @array = grep { $_ != $condition } @array;这工作正常,但我想要做的是基于一个单一的操作将原始数组拆分为两个......我认为我执行的操作数是严格必要的两倍。
帮助赞赏! 谢谢。
I have some perl code that looks something like this:
my @array = map { rand } ( 1..100 ); my @matching = grep { $_ == $condition } @array; @array = grep { $_ != $condition } @array;This works ok, but what I would like to do is split the original array into two based on a single operation...I think I'm carrying out twice as many operations as strictly necessary.
Help appreciated!! Thanks.
最满意答案
到目前为止,最简单的方法是迭代数组,并根据条件将值推送到两个数组中的任一个,如下例所示。
for (@array) { if ($_ % 2) {push @odd, $_} else {push @even, $_} }如果你想修改源数组:
for (my $i =0; $i < @array; ++$i) { if ($array[$i] % 2) { push @odd, splice (@array, $i--, 1); } }你为什么不推荐List :: MoreUtils :: part?
有问题的模块可能不存在于目标系统上,这总是令人讨厌的事情。
同样在系统上,我运行了测试,发现List::MoreUtils::part速度是本篇文章的第一个片段的两倍,尽管对于不同的part实现它实际上可能是相反的。
By far the easiest method is to iterate your array and push values to either of the two arrays depending on the condition, as in the below example.
for (@array) { if ($_ % 2) {push @odd, $_} else {push @even, $_} }If you'd like to modify the source array:
for (my $i =0; $i < @array; ++$i) { if ($array[$i] % 2) { push @odd, splice (@array, $i--, 1); } }Why didn't you recommend List::MoreUtils::part?
The module in question might not exists on the target system, which is always an annoying thing.
Also on the system I ran tests on I found that List::MoreUtils::part was twice as slow as first snippet in this post, though with different implementations of part it might be the opposite actually.
更多推荐
发布评论