不,但是有很多方法可以返回三个状态。
解决方案 1
- 空列表 (
return;
)
- 未定义 (
return undef;
)
- 字符串 (
return "foo";
)
my $found = my ($result) = search_struct($key, $data);
if ($found) {
print "$key: ", $result // "Undefined!", "\n";
}
else {
print "Sorry, no result was found for $key.\n";
}
标量上下文中的列表赋值计算为其右侧返回的元素数。
解决方案 2
- 错误 (
return undef;
)
- 引用未定义 (
return \undef;
)
- 引用字符串 (
return \"foo";
)
my $result = search_struct($key, $data);
if ($result) {
print "$key: ", $$result // "Undefined!", "\n"; # Note change here!
}
else {
print "Sorry, no result was found for $key.\n";
}
解决方案 3
- 错误 (
return 0;
)
- 真,且 undef (
return (1, undef);
)
- 真,字符串 (
return (1, "foo");
)
my ($found, $result) = search_struct($key, $data);
if ($found) {
print "$key: ", $result // "Undefined!", "\n";
}
else {
print "Sorry, no result was found for $key.\n";
}
解决方案 4
- 错误 (
return 0;
)
- 是的,undef 作为参数返回 (
$_[2] = undef; return 1;
)
- 是的,字符串作为参数返回 (
$_[2] = "foo"; return 1;
)
my $found = search_struct($key, $data, my $result);
if ($found) {
print "$key: ", $result // "Undefined!", "\n";
}
else {
print "Sorry, no result was found for $key.\n";
}
顺便说一句,我会将数据结构作为第一个参数传递,将键作为第二个参数传递。更像是面向对象编程。