【问题标题】:Perl script grepPerl 脚本 grep
【发布时间】:2016-05-06 22:14:54
【问题描述】:

脚本正在打印输入行的数量,我希望它打印另一个文件中存在的输入行的数量

#!/usr/bin/perl -w
open("file", "text.txt"); 
        @todd = <file>;         
        close "file";
while(<>){
        if( grep( /^$_$/, @todd)){
        #if( grep @todd, /^$_$/){
                print $_;
        }
        print "\n";
}

如果例如文件包含

1
3
4
5
7

并且将从中读取的输入文件包含

1
2
3
4
5
6
7
8
9

我希望它打印 1,3,4,5 和 7 但是正在打印 1-9

更新****** 这是我现在的代码,我收到了这个错误 ./may6test.pl 第 3 行关闭文件句柄 todd 上的 readline()。

#!/usr/bin/perl -w
open("todd", "<text.txt");
        @files = <todd>;         #file looking into
        close "todd";
while( my $line = <> ){
        chomp $line;
        if ( grep( /^$line$/, @files) ) {
                print $_;
        }
        print "\n";
}

这对我来说毫无意义,因为我有另一个脚本基本上在做同样的事情

#!/usr/bin/perl -w
open("file", "<text2.txt");    #
        @file = <file>;         #file looking into
        close "file";           #
while(<>){
        $temp = $_;
        $temp =~ tr/|/\t/;      #puts tab between name and id
        my ($name, $number1, $number2) = split("\t", $temp);
        if ( grep( /^$number1$/, @file) ) {
                print $_;
        }
}
print "\n";

【问题讨论】:

  • 这与 3 小时前的 this one 几乎相同。如果您是同一个人,我强烈建议不要重复发布来自不同帐户的帖子。否则,我建议您注意已经在 SO 上发布的相同问题。
  • 经验法则:避免出于这个原因隐式或显式使用$_mapgrep 是例外,因为需要使用它。

标签: perl grep


【解决方案1】:

好的,这里的问题是 - grep 也设置了 $_。所以grep { $_ } @array 将始终为您提供数组中的每个元素。

在基本层面 - 你需要:

while ( my $line = <> ) { 
   chomp $line; 
   if ( grep { /^$line$/ } @todd ) { 
      #do something
   }
}

但我建议您改为考虑构建行的哈希:

open( my $input, '<', "text.txt" ) or die $!;
my %in_todd = map { $_ => 1 } <$input>;
close $input;
while (<>) {
   print if $in_todd{$_};
}

注意 - 您可能需要注意尾随换行符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多