如何过滤匹配时如何通过数组grep?

时间:2021-01-30 03:51:51

Is there a quick and easy way to grep through an array finding the elements satisfying some test and remove these from the original array?

是否有一种快速简便的方法来查找数组,找到满足某些测试的元素并从原始数组中删除它们?

For example I would like

比如我想

@a = (1, 7, 6, 3, 8, 4);
@b = grep_filter { $_ > 5 } @a;

# now @b = (7, 6, 8)
# and @a = (1, 3, 4)

In other words, I want to split an array into two arrays: those which match and those which do not match a certain condition.

换句话说,我想将一个数组拆分成两个数组:匹配的数组和不符合某个条件的数组。

4 个解决方案

#1


9  

Know your libraries, mang.

知道你的图书馆,芒。

use List::MoreUtils qw(part);
part { $_>5 } (1, 7, 6, 3, 8, 4)

returns

(
    [1, 3, 4],
    [7, 6, 8],
)

#2


8  

my @a = (1, 7, 6, 3, 8, 4);
my (@b, @c);    

push @{ $_ > 5 ? \@b : \@c }, $_ for @a;

#3


3  

Using libraries is good, but for completeness, here is the function as specified in the question:

使用库是好的,但为了完整性,这里是问题中指定的函数:

sub grep_filter (&\@) {
    my ($code, $src) = @_;
    my ($i, @ret) = 0;
    local *_;
    while ($i < @$src) {
        *_ = \$$src[$i];
        &$code
            ? push @ret, splice @$src, $i, 1
            : $i++
    }
    @ret
}

my @a = (1, 7, 6, 3, 8, 4);
my @b = grep_filter {$_ > 5} @a;

say "@a"; # 1 3 4
say "@b"; # 7 6 8

#4


-1  

Is this what you want?

这是你想要的吗?

@a = (1, 7, 6, 3, 8, 4);
@b = grep_filter { $_ > 5 } @a;
@a = grep_filter { $_ < 5 } @a;

do another grep with your condition negated.

在你的病情被否定的情况下再做一次grep。

#1


9  

Know your libraries, mang.

知道你的图书馆,芒。

use List::MoreUtils qw(part);
part { $_>5 } (1, 7, 6, 3, 8, 4)

returns

(
    [1, 3, 4],
    [7, 6, 8],
)

#2


8  

my @a = (1, 7, 6, 3, 8, 4);
my (@b, @c);    

push @{ $_ > 5 ? \@b : \@c }, $_ for @a;

#3


3  

Using libraries is good, but for completeness, here is the function as specified in the question:

使用库是好的,但为了完整性,这里是问题中指定的函数:

sub grep_filter (&\@) {
    my ($code, $src) = @_;
    my ($i, @ret) = 0;
    local *_;
    while ($i < @$src) {
        *_ = \$$src[$i];
        &$code
            ? push @ret, splice @$src, $i, 1
            : $i++
    }
    @ret
}

my @a = (1, 7, 6, 3, 8, 4);
my @b = grep_filter {$_ > 5} @a;

say "@a"; # 1 3 4
say "@b"; # 7 6 8

#4


-1  

Is this what you want?

这是你想要的吗?

@a = (1, 7, 6, 3, 8, 4);
@b = grep_filter { $_ > 5 } @a;
@a = grep_filter { $_ < 5 } @a;

do another grep with your condition negated.

在你的病情被否定的情况下再做一次grep。