【问题标题】:In Perl, how to avoid opening files multiple times在 Perl 中,如何避免多次打开文件
【发布时间】:2012-12-06 22:31:17
【问题描述】:

我需要从一个文件中读取,遍历它并将该行写入另一个文件。当行数达到阈值时,关闭输出文件句柄并打开一个新句柄。

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

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;

【问题讨论】:

  • 不要在 for 循环中打开和关闭文件。将 open 命令移到 for 循环上方。

标签: file loops perl


【解决方案1】:

仅在更改 $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, 10, 5 );       

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

【讨论】:

  • +1 但我认为你应该只保留答案的第二部分。
  • 您可以在底部添加:if(tell($fop) != -1) { close $fop; } 关闭它。
  • 您应该在打开文件时始终进行错误检查。当然,除非您使用的是autodie 模块。你是哪个。 :)
  • @Tiger-222, $fop 应该始终在程序结束时打开,所以我认为标准的close 应该没问题。在像这样的小脚本中,完全不用关闭并让 Perl 担心清理工作也可以。
  • 是的,你是对的,一个简单的close 就足够了;我只是指出它;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 2014-08-22
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
相关资源
最近更新 更多