【发布时间】:2012-12-06 22:31:17
【问题描述】:
我需要从一个文件中读取,遍历它并将该行写入另一个文件。当行数达到阈值时,关闭输出文件句柄并打开一个新句柄。
如何避免每次从输入文件句柄中读取一行时打开和关闭输出文件句柄,如下所示?
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;
【问题讨论】:
-
不要在 for 循环中打开和关闭文件。将
open命令移到 for 循环上方。