How can I grep through an array and also filter matches?

Is there a quick and easy way to grep through an array that finds elements that satisfy some tests and removes them 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 that match, and those that don't match a particular condition.

+5
source share
4 answers

Know your libraries, mang.

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

returns

(
    [1, 3, 4],
    [7, 6, 8],
)
+9
source
my @a = (1, 7, 6, 3, 8, 4);
my (@b, @c);    

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

, , , :

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
+3

, ?

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

grep .

-1
source

All Articles