让我们假设我有一个子do_foo
来做一些操作。它可以成功终止并返回true,或者由于多种原因而没有根据类状态执行所需的操作并返回false。
sub do_foo {
my $self = shift;
my $status = 1; # Assume by default success operation
my $error; # How to handle failed operation reason in this variable ?
# Do some process here, based on it change operation status to 0
# The error will also be set to identify why operation failed in case of failure
# ....
return $status;
}
我在想什么是返回操作失败原因的最佳设计?
以下是我的尝试:
:一种。在数组上下文中返回一个列表,其中包含有关错误的额外信息
(1)
是,则返回列表wantarray
true,标量1
否则(0, $error)
为真,则为wantarray
,否则标量为0
B中。此外,我考虑在操作失败的情况下抛出异常,但我不想在预期情况/情景/流程的情况下返回异常,可以无异常地处理。 我的理解是,例外仅适用于特殊情况 - 即,它们不属于正常代码流的一部分。
总而言之,我的问题是:
use constant
?或者是什么 ? (顺便说一句,我知道PBP 4.5反对use constant
)