简体   繁体   中英

In Perl, how to avoid opening files multiple times

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM