如何让 Perl 在引用 undef 值时停止?
当您引用 undef 值时,如何让 Perl 停止并给出堆栈跟踪,而不仅仅是警告? 似乎 use strict;
不足以达到此目的。
How do you get Perl to stop and give a stack trace when you reference an undef value, rather than merely warning? It seems that use strict;
isn't sufficient for this purpose.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不用像其他人建议的那样乱七八糟地摆弄
%SIG
,只需使用Carp::Always
就完成了。请注意,您只需使用
perl -MCarp::Always
运行脚本即可将模块注入到脚本中,而无需修改源代码。 此外,您可以将PERL5OPT
环境变量设置为-MCarp::Always
来加载它,甚至无需更改脚本的调用。 (请参阅perldoc perlrun
。)Instead of the messy fiddling with
%SIG
proposed by everyone else, justuse Carp::Always
and be done.Note that you can inject modules into a script without source modifications simply by running it with
perl -MCarp::Always
; furthermore, you can set thePERL5OPT
environment variable to-MCarp::Always
to have it loaded without even changing the invocation of the script. (Seeperldoc perlrun
.)包含以下内容:
然后在源文件的顶部包含以下行中的一行:
confess
行将提供堆栈跟踪,cluck
行将提供堆栈跟踪线路更加简洁。Include this:
Then include one of these lines at the top of your source file:
The
confess
line will give a stack trace, and thecluck
line is much more terse.第一行使警告变得致命。 当程序终止时,接下来的两个会导致堆栈跟踪。
另请参阅
man 3pm warnings
了解更多详细信息。The first line makes the warning fatal. The next two cause a stack trace when your program dies.
See also
man 3pm warnings
for more details.引用 undef 值本身不会有问题,但如果您的代码期望它是 undef 以外的值,则可能会导致警告。 (特别是如果您尝试使用该变量作为对象引用)。
您可以在代码中添加一些内容,例如:
Referencing an undef value wouldn't be a problem in itself, but it may cause warnings if your code is expecting it to be something other than undef. (particularly if you're trying to use that variable as an object reference).
You could put something in your code such as:
使这些警告致命的一种方法是为 WARN 虚拟信号安装信号处理程序:
One way to make those warnings fatal is to install a signal handler for the WARN virtual-signal:
您必须手动执行此操作。 上面的“答案”不起作用! 只需测试一下:
您将看到取消引用不会导致任何错误消息或警告。 我不知道有什么办法可以让 Perl 自动检测到 undef 的使用作为无效引用。 我怀疑这是设计使然,因此自动生存可以无缝地进行。
You have to do this manually. The above "answers" do not work! Just test out this:
You will see that dereferencing did not cause any error messages or warnings. I know of no way of causing Perl to automatically detecting the use of undef as an invalid reference. I suspect this is so by design, so that autovivification works seamlessly.