Perl:Grep的独特价值

时间:2015-07-16 04:44:27

标签: perl

基本上我想在我的Perl代码中使用shell脚本(grep pattern1 | grep pattern2)模拟管道grep操作,以使结果唯一。

下面的代码正在运行,胸围只是想知道这是正确的方法。请注意,我不想在这里引入内循环,只是为了grep部分。

foreach my $LINE ( @ARRAY1 ) {
    @LINES = split /\s+/, $LINE;
    @RESULT= grep ( /$LINES[0]/, ( grep /$LINES[1]/, @ARRAY2 ) );

...

3 个答案:

答案 0 :(得分:1)

这与你正在做的事情基本相同,“对于每个@ARRAY2元素,检查它是否与@LINES中的所有元素匹配”(只要@LINES中的任何一个停止元素不匹配),

use List::Util "none";
my @RESULT= grep { my $s = $_; none { $s !~ /$_/ } @LINES } @ARRAY2;

# index() is faster for literal values
my @RESULT= grep { my $s = $_; none { index($s, $_) <0 } @LINES } @ARRAY2;

答案 1 :(得分:1)

无需级联对grep的调用 - 您只需条件

同样值得一提的是,您应该使用小写字母作为标识符,而split /\s+/几乎应始终为split ' '

这是我要写的内容

for my $line ( @array1 ) {
    my @fields = split ' ', $line;
    my @result = grep { /$fields[0]/ and /$fields[1] } @array2;

    ...

}

答案 2 :(得分:0)

在perl中有不同的方法从数组中grep / extract唯一值。

##2) Best of all
my %hash = map { $_ , 1 } @array;
my @uniq = keys %hash;
print "\n Uniq Array:", Dumper(\@uniq);

##3) Costly process as it involves 'greping'
my %saw;
my @out = grep(!$saw{$_}++, @array);
print "\n Uniq Array: @out \n";