如何使用IO::File perl捕获错误

如何使用IO::File perl捕获错误,perl,file-io,Perl,File Io,通常你会: open( my $fh, "+<", "$thefile.txt") or die "Could not open $thefile.txt $!\n"; open(my$fh),+$fh->open(open(“close; } 否则{ 死亡(“无法打开文件。原因:$!”; } 打开(my$fh),+从文档中: 建造师 new(文件名[,模式[,PERMS]]) 创建一个IO::File。如果它收到任何参数,它们将被传递给方法;如果打开失败,对象将被销毁。否则,它将返回

通常你会:

open( my $fh, "+<", "$thefile.txt") or die "Could not open $thefile.txt $!\n";
open(my$fh),+
$fh->open(
如果无法打开文件,则将为false。因此只需添加一个
否则

$fh = new IO::File;
if ($fh->open("< file")) {
    print <$fh>;
    $fh->close;
}
else {
    die("Cannot open file.  Reason: $!");
}
$fh=新IO::文件;
如果($fh->open(“close;
}
否则{
死亡(“无法打开文件。原因:$!”;
}
打开(my$fh),+从文档中:

建造师

  • new(文件名[,模式[,PERMS]])

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

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

use IO::File;

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

无法打开:script.pl第5行没有这样的文件或目录。

但是有没有办法找到无法打开的原因?@a7omiton IO::File在后台使用标准的Perl
open
函数,因此无法打开将设置
$!
变量。
 open( my $fh, "+<", "thefile.txt") or die "Could not open thefile.txt $!\n";
$file = 'thefile.txt';
open( my $fh, "<", "$file") or die "Could not open $file $!\n"
use IO::File;

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