如何打印不匹配的行?

时间:2012-06-21 21:13:49

标签: perl

我编写的脚本输出文件2中的所有行,这些行以文件1中的数字开头。

问题

如何输出所有其他未匹配的行?

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my @res;

open(FILE, '<', "1") or die $!;
while (defined (my $line = <FILE>)) {
  chomp $line;
  push @res, $line;
}
close FILE;

open(FILE, '<', "2") or die $!;
while (defined (my $line = <FILE>)) {
  chomp $line;
  $line =~ m/(\d+)/;

  if (defined $1) {
    foreach my $a (@res) {
      if ($a == $1) {
        print $line . "\n";
      }
    }
  }
}
close FILE;

档案1

155
156
157
158
159
160

文件2

150 a
151 f
152 r
153 a
154 a
155 a
156 a
157 f
158 f
159 f

2 个答案:

答案 0 :(得分:5)

你的答案实际上非常接近:这足以改变这个

foreach my $a (@res) {
  if ($a == $1) {
    print $line . "\n";
  }
}

......对此...

my $found;
foreach my $a (@res) {
  if ($a eq $1) { # we compare strings, not numbers, even if these strings are 'numeric'
    $found = 1;
    print $line . "\n";
    last; # no need to look further, we already found an item
  }
}
print "Not matched: $line", "\n" unless $found; 

但仍有一些事情可以谈论。 )看,因为第一个文件中的所有这些数字字符串都是唯一的,所以使用哈希来存储它们要好得多。代码实际上不会改变那么多:

my %digits;
... # in the first file processing loop:
$digits{$line} = 1;
... # in the second file processing loop, instead of foreach:
if ($digits{$1}) { 
  print $line, "\n"; 
} else {
  print "Not matched: $line", "\n";
}

但关键是在哈希搜索比一次又一次地遍历数组要快得多。 )

答案 1 :(得分:0)

use strict;
use warnings;

my %res;

open(FILE, '<', "1") or die $!;
while (defined (my $line = <FILE>)) {
  chomp $line;
  $res{$line} = 1;
}
close FILE;

open(FILE, '<', "2") or die $!;
while (defined (my $line = <FILE>)) {
  if ($line =~ m/(\d+)/) {
      print $line if not $res{$1};
  }
}
close FILE;