2014-01-21 30 views
0

我做了一個perl腳本,它直接從第一個文件的內容創建一個散列,然後讀取第二行的每一行,檢查散列是否應該打印。重定向文件中的結果

這裏是perl腳本:

use strict; 
use warnings; 
use autodie; 

my %permitted = do { 
open my $fh, '<', 'f1.txt'; 
map { /(.+?)\s+\(/, 1 } <$fh>; 
}; 

open my $fh, '<', 'f2.txt'; 
while (<$fh>) { 
my ($phrase) = /(.+?)\s+->/; 
print if $permitted{$phrase}; 
} 

我找我如何打印出一個文本文件的結果,因爲這個腳本實際上在屏幕上打印結果。

預先感謝您。

親切

回答

2
$ perl thescript.pl > result.txt 

將運行腳本,並把打印輸出result.txt

或者,從劇本本身:

use strict; 
use warnings; 
use autodie; 

my %permitted = do { 
    open my $fh, '<', 'f1.txt'; 
    map { /(.+?)\s+\(/, 1 } <$fh>; 
}; 

# Open result.txt for writing: 
open my $out_fh, '>', 'result.txt' or die "open: $!"; 

open my $fh, '<', 'f2.txt'; 
while (<$fh>) { 
    my ($phrase) = /(.+?)\s+->/; 
    # print output to result.txt 
    print $out_fh $_ if $permitted{$phrase}; 
} 
2

以寫模式打開一個新的文件句柄,然後打印到它。請參閱perldoc -f打印或http://perldoc.perl.org/functions/print.html更多信息

... 
open my $fh, '<', 'f2.txt'; 
open my $out_fh, '>', 'output.txt'; 
while (<$fh>) { 
    my ($phrase) = /(.+?)\s+->/; 
    print $out_fh $_ 
     if $permitted{$phrase}; 
} 
+1

你實際上需要明確指定'$ _',否則它會向終端輸出GLOB(0x ...)。所以'print $ out_fh $ _ if ...' – grebneke

+0

謝謝... brainfart :) –

2

map平該文件的內容首先產生文件的所有行的列表。這不一定是壞事,除非文件相當大。 grebneke顯示瞭如何使用> result.txt將輸出指向文件。鑑於此,以及(可能)map問題,只考慮這兩個文件從命令行傳遞到腳本,並使用while S程序他們:

use strict; 
use warnings; 

my %permitted; 

while (<>) { 
    $permitted{$1} = 1 if /(.+?)\s+\(/; 
    last if eof; 
} 

while (<>) { 
    print if /(.+?)\s+->/ and $permitted{$1}; 
} 

用法:perl script.pl f1.txt f2.txt > result.txt

希望這有助於!