我正在编写一个搜索例程,其中undefined和zero都是有效的结果.我正在返回一个两元素数组,($result, $answer)因为我没有"未定义但真实"的值.它工作正常,但有点klutzy.一堂课似乎有点矫枉过正.
这样的事情是否存在或者可以以某种方式伪造?我正在考虑诸如0E0技巧之类的东西等.
更多细节.这是我想要的用户界面.当前例程返回两个值,结果(无论是否找到键)和值(如果是).
my $result = search_struct($key, $complex_data_structure);
if ($result) {
print "A result was found for $key! Value is: ", $result // "Undefined!", "\n";
}
else {
print "Sorry, no result was found for $key.\n";
}
Run Code Online (Sandbox Code Playgroud)
您可以只返回对结果的引用.对于任何其他结果undef,\( undef )对于文字未定义结果,不返回\( whatever )任何结果.然后调用者可以使用$$result(在确定$result定义之后).
不,但有很多方法可以让你回归三个州.
解决方案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";
}
Run Code Online (Sandbox Code Playgroud)
标量上下文中的列表赋值计算为其右侧返回的元素数.
解决方案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";
}
Run Code Online (Sandbox Code Playgroud)
解决方案3
return 0;)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";
}
Run Code Online (Sandbox Code Playgroud)
解决方案4
return 0;)$_[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";
}
Run Code Online (Sandbox Code Playgroud)
顺便说一下,我将数据结构作为第一个参数传递,将密钥作为第二个参数传递.更像是OO编程.