【问题标题】:How to catch errors with IO::File perl如何使用 IO::File perl 捕获错误
【发布时间】:2014-08-20 05:09:19
【问题描述】:

通常你会这样做:

open( my $fh, "+<", "$thefile.txt") or die "Could not open $thefile.txt $!\n";

但是使用 IO::File 你可以(来自文档):

$fh = new IO::File;
if ($fh->open("< file")) {
    print <$fh>;
    $fh->close;
}

如果打开文件时出现问题,IO::File 是否会自动抛出错误/死机?使用这个模块的时候会怎么做呢?

主要与日志记录有关,您将如何注销“没有这样的文件或目录”之类的“好”错误消息

【问题讨论】:

    标签: perl file-io


    【解决方案1】:

    来自IO::File 的文档:

    构造器

    • new ( FILENAME [,MODE [,PERMS]] )

      创建一个IO::File。如果它接收到任何参数,则将它们传递给方法open;如果打开失败,则对象被销毁。否则,返回给调用者。

    因此,您可以像平常一样使用or die 语句:

    use IO::File;
    
    my $fh = IO::File->new('notfound.txt') or die "Can't open: $!";
    

    输出:

    Can't open: No such file or directory at script.pl line 5.
    

    【讨论】:

      【解决方案2】:
       open( my $fh, "+<", "thefile.txt") or die "Could not open thefile.txt $!\n";
      

      从文件.txt 中删除 $ 符号。您没有将文件名存储在变量中。

      你可以使用

      $file = 'thefile.txt';
      open( my $fh, "<", "$file") or die "Could not open $file $!\n"
      

      “$!”将显示错误消息为“没有这样的文件或目录”

      【讨论】:

        【解决方案3】:

        $fh-&gt;open("&lt; file") 如果无法打开文件,则为 false。所以只需添加一个else

        $fh = new IO::File;
        if ($fh->open("< file")) {
            print <$fh>;
            $fh->close;
        }
        else {
            die("Cannot open file.  Reason: $!");
        }
        

        【讨论】:

        • 但是有什么办法可以得到打不开的原因吗?
        • @a7omiton IO::File 在后台使用标准 Perl open 函数,因此打开失败将设置$! 变量。
        猜你喜欢
        • 1970-01-01
        • 2013-01-13
        • 2014-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        相关资源
        最近更新 更多