In Perl, how to avoid opening files multiple times

I need to read from a file, iterate over it and write a line to another file. When the number of lines reaches the threshold, close the output file descriptor and open a new one.

How to avoid opening and closing the output file descriptor every time I read a line from the input file descriptor, as shown 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; 
+8
file loops perl perl5
source share
1 answer

Open the file only when $postfix changes. In addition, you can get a little easier.

 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; 
+11
source share

All Articles