2012-06-21 47 views
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

需要注意的是,如果你的平臺提供了一個POSIX兼容的'grep'命令,你可以用'grep的-f1 2'和'grep的-v -f1 2'更換你的腳本。 (第一個如果你想要當前腳本;第二個如果你想要[raina77ow的版本](http://stackoverflow.com/a/11146936/377270)。) – sarnold

+0

'while'中定義的(defined(my $ line = ))'是多餘的。但是,在最小適用範圍內使用詞法文件句柄而不是包全局裸句文件句柄的好處不是。 –

回答

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

但重點是在哈希中搜索比循環一次又一次的數組快得多。 )

+0

..你打算談談使用散列而不是列表嗎? – sarnold

+1

當然。 )這個任務實際上是乞求哈希被引入。 ) – raina77ow

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;