私が書いたスクリプトは、ファイルからすべての行を出力します 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
回答:
回答№1は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";
}
ただし、重要なのは、ハッシュでの検索は、配列を何度もループするよりもはるかに高速であるということです。 )。
回答№2の場合は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;