Perl:打开还是[代码块]?

Zyz*_*zyx 5 perl

我正在运行脚本 A,它将包含文件路径的 ARGV 提供给 perl 脚本 B。这是由

local @ARGV = ($file, $file2, etc.);
do scriptB.pl or die "scriptB has failed";
Run Code Online (Sandbox Code Playgroud)

脚本 B 然后尝试打开文件:

open( my $fh_file, "<", $file )  
  or die "Could not open file '$file' $!"; 
Run Code Online (Sandbox Code Playgroud)

但是,如果文件丢失,我不会在 B 中的“or die”之后收到消息。而是在 A 中收到 do scriptB.pl or die 消息。如果我从 A 中删除“or die”,脚本将继续在 B 默默地死去之后,好像什么都没发生一样。

我想知道有没有办法让 B 打印它的死亡信息?

更好的是,让 B 在无法打开文件后运行代码块的最佳方法是什么?例如,所述代码将写入一个单独的文件,列出哪些文件丢失,以便用户可以轻松地追踪此类错误。

#something like
open( my $fh_file, "<", $file) or { 
print "the file could not be found";
die;
}
Run Code Online (Sandbox Code Playgroud)

我在网上搜索帮助时发现的唯一一件事是有人提到了“or do {}”,但这给了我奇怪的语法错误,所以我不确定我是否正确使用它。

Dav*_*oss 8

如果您想继续使用该open(...) or ...语法,则可以使用do.

open my $fh, '<', $file or do {
  ...
};
Run Code Online (Sandbox Code Playgroud)

但我认为切换到可能更清楚 if

if (! open my $fh, '<', $file) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

甚至 unless

unless (open my $fh '<', $file) {
  ...
}
Run Code Online (Sandbox Code Playgroud)