我需要從一個文件讀取數據,遍歷它並將該行寫入另一個文件。當行數達到閾值時,關閉輸出文件句柄並打開一個新句柄。在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;
不要在for循環中打開和關閉文件。在for循環上移動'open'命令。 –