How can I grep through an array, while filtering out matches?
Is there a quick and easy way to grep th开发者_JS百科rough 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.
Know your libraries, mang.
use List::MoreUtils qw(part);
part { $_>5 } (1, 7, 6, 3, 8, 4)
returns
(
[1, 3, 4],
[7, 6, 8],
)
my @a = (1, 7, 6, 3, 8, 4);
my (@b, @c);
push @{ $_ > 5 ? \@b : \@c }, $_ for @a;
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
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.
精彩评论