perl - 使用 $@ 传递模块中的错误消息

标签 perl

我一直在研究一个现在未维护的 CPAN 模块的分支(据我所知)。在这个模块中,他们使用 $@将错误消息向上传递到堆栈。换句话说,他们设置了$@如果对子例程的任何调用出现任何问题,它们会在调用后检查它是否已设置。我以前从未见过这个变量,但我认为它很有用,所以我开始在代码中以同样的方式使用它。现在我最近阅读了更多关于它的内容,发现它的目的比这更窄一些。阅读 perlvar (以及关于此事的其他 SO 问题)并没有为我完全回答这个问题,但是,使用 $@ 可以吗?这边走?我知道的一些“标点符号”变量绝对不应该以这种通用方式使用(有些甚至使用 local ),这是其中一种情况,还是我可以继续这种做法?

最佳答案

$@通常不明确设置。相反,它会在引发异常时自动为您设置。来自 perldoc die :

  • die LIST

    die raises an exception. Inside an eval the error message is stuffed into $@ and the eval is terminated with the undefined value. If the exception is outside of all enclosing evals, then the uncaught exception prints LIST to STDERR and exits with a non-zero value. If you need to exit the process with a specific exit code, see exit.



例如,
#!/usr/bin/perl

eval {
    print "Hi\n";
    die "Something went wrong here";
    print "Bye\n";
};
print $@;

打印

Hi
Something went wrong here at ./cr22854919 line 5.

允许使用$@以这种方式将错误消息向上传递到堆栈,作为一种 try-catch 机制。但是,由于它是一个全局变量,您应该在 eval { } 之后尽快处理它。 block 以确保没有其他代码干扰您对异常的处理。

另一个常用于错误处理的魔法变量是$!。 ,其作用类似于 errno在 C.

例子:
my $path = "/tmp/no-such-file";
open F, '<', $path
    or print STDERR "$path: $!\n";

输出:

/tmp/no-such-file: No such file or directory

关于perl - 使用 $@ 传递模块中的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22854919/

相关文章:

bash - Bash 中的 Perl : How to read from pipe and pass arguments to perl at the same time?

linux - 如果我安装了 SIGCHLD 处理程序,对特定 pid 的 *blocking* 等待是否仍然有效?

perl - 检测单行中的第一个或第二个文件

arrays - 是字符串中包含的任何数组项

Perl 替换一个字符串

Perl glob 奇怪的行为

perl - 在 void 上下文中无用地使用负模式绑定(bind) (!~)

perl - 寻找棕榈星期日

perl - 创建一个无效的 UTF8 perl 字符串?

Perl LWP 手动关闭连接