如何在 Perl 中终止程序 - 退出还是死亡? [英] How to terminate a program in Perl - exit or die?

查看:121
本文介绍了如何在 Perl 中终止程序 - 退出还是死亡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用语法检查来查看我的 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,并不是每个人都知道该怎么做).因此,使用 dieprintexit 哪个在很大程度上取决于您正在编写的程序类型.

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 an eval, 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 中终止程序 - 退出还是死亡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆