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 に答える