在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;

解决方法

只有在更改$postfix时才重新打开文件.此外,你可以更简单一些.
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,5 );       

    if ($tot >= $threshold) {
        $tot = 0;
        $postfix++;
        close $fop;
        open $fop,'output_' . $postfix; 
    }
    print {$fop} $line;
}
close $fip;
close $fop;

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...