我一直在研究一个现在未维护的 CPAN 模块的分支(据我所知)。在这个模块中,他们使用 $@
将错误消息向上传递到堆栈。换句话说,他们设置了$@
如果对子例程的任何调用出现任何问题,它们会在调用后检查它是否已设置。我以前从未见过这个变量,但我认为它很有用,所以我开始在代码中以同样的方式使用它。现在我最近阅读了更多关于它的内容,发现它的目的比这更窄一些。阅读 perlvar (以及关于此事的其他 SO 问题)并没有为我完全回答这个问题,但是,使用 $@
可以吗?这边走?我知道的一些“标点符号”变量绝对不应该以这种通用方式使用(有些甚至使用 local
),这是其中一种情况,还是我可以继续这种做法?
最佳答案
$@
通常不明确设置。相反,它会在引发异常时自动为您设置。来自 perldoc die
:
die LIST
die
raises an exception. Inside aneval
the error message is stuffed into$@
and theeval
is terminated with the undefined value. If the exception is outside of all enclosingeval
s, then the uncaught exception prints LIST toSTDERR
and exits with a non-zero value. If you need to exit the process with a specific exit code, seeexit
.
例如,
#!/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/