0

我编写的脚本输出文件中所有以文件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
4

2 回答 2

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";
}

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

于 2012-06-21T21:20:46.513 回答
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;
于 2012-06-22T04:31:15.820 回答