我寫的腳本輸出文件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
需要注意的是,如果你的平臺提供了一個POSIX兼容的'grep'命令,你可以用'grep的-f1 2'和'grep的-v -f1 2'更換你的腳本。 (第一個如果你想要當前腳本;第二個如果你想要[raina77ow的版本](http://stackoverflow.com/a/11146936/377270)。) – sarnold
'while'中定義的(defined(my $ line =))'是多餘的。但是,在最小適用範圍內使用詞法文件句柄而不是包全局裸句文件句柄的好處不是。 –