问题描述
我正在使用语法检查来查看我的 Perl 脚本是否以正确的方式使用.如果语法不正确,我会显示一条消息,说明正确的语法是什么,然后结束程序的执行.
I am using syntax checking to see whether my Perl script is being used in the correct way. If the syntax is not correct, I display a message saying what the correct syntax is, and then end the execution of the program.
之间:
print "Please use the following syntax: ...";
exit 1;
和:
die("Please use the following syntax: ...");
我应该使用哪一种?我知道如果异常处理到位,die
将是答案,但事实并非如此.
Which one should I use? I know die
would have been the answer if exception handling was in place, but that is not the case.
没有异常处理的程序终止,哪个更好?还请说明原因.
Which one is the better choice for program termination without exception handling? Please also say why.
推荐答案
这取决于您希望使用 STDERR 和 STDOUT 发生什么.我更喜欢向 STDERR 发送错误和警告类型的消息,这样当有人尝试将输出重定向到文件时,他们仍然可以看到错误消息;但是,有时 STDOUT 用于向用户传达状态以便他或她可以 tail -f
或对其进行分页,而在那些时候写入 STDERR 会导致他们痛苦(他们必须重定向STDERR 使用 2>&1
返回 STDOUT,并不是每个人都知道该怎么做).因此,使用 die
或 print
和 exit
哪个在很大程度上取决于您正在编写的程序类型.
It depends on what you want to have happen with STDERR and STDOUT. I prefer to send error and warning type messages to STDERR so that when someone is trying to redirect output to a file they still see the error messages; However, there are times though when STDOUT is used to communicate status to the user so he or she can tail -f
or paginate it, and at those times writing to STDERR causes them pain (they have to redirect STDERR back into STDOUT with 2>&1
, and not everyone knows how to do that). So which to use, die
or print
and exit
, depends heavily on what type of program you are writing.
使用 die
还有其他好处/缺点:
There are other benefits/drawbacks to using die
:
- 您可以使用
eval
捕获die
,但不能退出 - 您可以通过为
__DIE__
信号安装信号处理程序,在程序调用die
时运行代码 - 您可以轻松覆盖
die
函数
- You can trap
die
with aneval
, but not exit - You can run code when the program calls
die
by installing a signal handler for the__DIE__
signal - You can easily override the
die
function
每个人都有可以轻松完成它们的时候,也有可以完成它们的痛苦的时候.
Each of those has times where it is handy to be able to do them, and times when it is a pain that they can be done.
这篇关于如何在 Perl 中终止程序 - 退出还是死亡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!