2012-12-19 44 views
8

我需要從一個文件讀取數據,遍歷它並將該行寫入另一個文件。當行數達到閾值時,關閉輸出文件句柄並打開一個新句柄。在Perl中,如何避免多次打開文件

如何避免每次從輸入文件句柄中讀取一行時打開和關閉輸出文件句柄?

use autodie qw(:all); 

my $tot  = 0; 
my $postfix = 'A'; 
my $threshold = 100; 

open my $fip, '<', 'input.txt'; 
LINE: while (my $line = <$fip>) { 
    my $tot += substr($line, 10, 5);  
    open my $fop, '>>', 'output_' . $postfix; 
    if ($tot < $threshold) { 
     print {$fop} $line; 
    } 
    else { 
     $tot = 0; 
     $postfix++; 
     redo LINE; 
    } 
    close $fop; 
} 
close $fip; 
+3

不要在for循環中打開和關閉文件。在for循環上移動'open'命令。 –

回答

11

只有當您更改$postfix時才重新打開該文件。此外,你可以更簡單一些。

use warnings; 
use strict; 
use autodie qw(:all); 

my $tot  = 0; 
my $postfix = 'A'; 
my $threshold = 100; 

open my $fop, '>>', 'output_' . $postfix; 
open my $fip, '<', 'input.txt'; 
while (my $line = <$fip>) { 
    $tot += substr($line, 10, 5);  

    if ($tot >= $threshold) { 
     $tot = 0; 
     $postfix++; 
     close $fop; 
     open $fop, '>>', 'output_' . $postfix; 
    } 
    print {$fop} $line; 
} 
close $fip; 
close $fop; 
+2

+1,但我認爲你應該只保留答案的第二部分。 –

+0

你可以在底部添加:'if(tell($ fop)!= -1){close $ fop; }'關閉它。 –

+4

打開文件時,應始終檢查錯誤。當然,除非你使用'autodie'模塊。你是誰。 :) – TLP