I need to read from a file, iterate through it and write the line to another file. When the number of lines reach a threshold, close the output file handle and open a new one.
How do I avoid opening and closing the output file handle every time I read a line from the input file handle as below?
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;
Only reopen the file when you change $postfix
. Also, you can get a bit simpler.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With