Perl script grep



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

#!/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正在打印而不是

更新******这是我的代码,我收到了这个错误位于的已关闭文件句柄todd上的readline()/5月6日测试.pl第3行。

#!/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";

好吧,这里的问题是-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{$_};
}

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

最新更新