加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:42:37 所属栏目:大数据 来源:网络整理
导读:我需要从文件中读取,遍历它并将该行写入另一个文件.当行数达到阈值时,关闭输出文件句柄并打开一个新句柄. 每次从输入文件句柄读取一行时,如何避免打开和关闭输出文件句柄? use autodie qw(:all);my $tot = 0;my $postfix = 'A';my $threshold = 100;open my
我需要从文件中读取,遍历它并将该行写入另一个文件.当行数达到阈值时,关闭输出文件句柄并打开一个新句柄.

每次从输入文件句柄读取一行时,如何避免打开和关闭输出文件句柄?

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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读