2012-12-19 30 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