简体   繁体   English

在Perl中,如何避免多次打开文件

[英]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 . 只有在更改$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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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