【问题标题】:Perl read file errorPerl 读取文件错误
【发布时间】:2012-07-21 16:29:49
【问题描述】:

我必须使用 perl 逐行读取内存中的一个大 (BIG) 文件。 如果出现错误,函数 open() 会返回 false 和 $!设置为系统错误。 但是,如果我在读取文件时遇到一些错误? 我使用此代码:

open(STATISTICS, "<" . $statisticsFile) or die "Can't open statistics file $statisticsFile ($!)";
while (<STATISTICS>) {
  my $line = $_;
  ...
}
close($STATISTICS);

有什么提示吗?

【问题讨论】:

  • 任何读取错误:说磁盘在完成读取文件之前着火了吗?
  • 另见perldoc -f readline: while ( ! eof($fh) ) { defined( $_ = &lt;$fh&gt; ) or die "readline failed: $!"; ... }
  • 你也可以在循环体中测试$filehandle-&gt;error。见 IO::句柄

标签: perl file-io


【解决方案1】:

您可以更改您的代码以使其工作,如下所示。

您似乎同时使用STATISTICS$STATISTICS 作为文件句柄。由于词法句柄是可取的,我在这里使用了$stat

open my $stat, "<" . $statisticsFile
    or die "Can't open statistics file $statisticsFile: $!";

until (eof $stat) {
  my $line = <$stat>;
  defined $line or die "Read failure on statistics file $statisticsFile: $!";
  ...
}

close($stat);

【讨论】:

  • 是的,谢谢,我的错!刚刚编辑的问题。你的答案是正确的,因为如果你不测试 eof while reading 文件,你不会得到错误,循环永远不会结束...... :-(
  • 我又错了,对不起...循环结束,即使有其他答案行为,但我更喜欢这种方法...它甚至不慢...
【解决方案2】:

如果出现错误,while 循环会中断,因为&lt;STATISTICS&gt; 返回undef。应该设置$!,这样你就可以在循环之后检查$!的值,看看是否一切正常。

【讨论】:

    【解决方案3】:

    您可能想在 while 循环之后测试 eof。如果你不在 eof 你有一个错误。或者,可能更安全,检查 $!因为 eof 可能重置 $!。无论哪种方式都可以测试。

    我还要补充一点,在 read(2) 上出现错误是非常罕见的。也许您的内存不足。

    如果你确实用完了内存,perl 不会告诉你这件事,操作系统会(通过杀死 perl!)。

    【讨论】:

    • 谢谢。但是,我没有(还)收到错误,我只是为了安全起见...... ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 2017-08-05
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多