问题描述
我有一个管理错误检查的 Perl 例程.大约有 10 种不同的检查,有些是嵌套的,基于先前的成功.这些通常不是我需要croak
/die
的例外情况.此外,一旦发生错误,就没有必要运行其余的检查.
I have a Perl routine that manages error checking. There are about 10 different checks and some are nested, based on prior success. These are typically not exceptional cases where I would need to croak
/die
. Also, once an error occurs, there's no point in running through the rest of the checks.
但是,我似乎想不出一个巧妙的方法来解决这个问题,除非使用类似于以下可怕的 hack 的方法:
However, I can't seem to think of a neat way to solve this issue except by using something analogous to the following horrid hack:
sub lots_of_checks
{
if(failcond)
{
goto failstate:
}
elsif(failcond2)
{
goto failstate;
}
#This continues on and on until...
return 1; #O happy day!
failstate:
return 0; #Dead...
}
我希望能够做的事情是这样的:
What I would prefer to be able to do would be something like so:
do
{
if(failcond)
{
last;
}
#...
};
推荐答案
与返回 0
相比,空的 return 语句是从 Perl 子程序返回 false
的更好方法.后一个值在列表上下文中实际上为真:
An empty return statement is a better way of returning false
from a Perl sub than returning 0
. The latter value will actually be true in list context:
sub lots_of_checks {
return if fail_condition_1;
return if fail_condition_2;
# ...
return 1;
}
这篇关于如何干净地处理 Perl 中的错误检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!