I'm writing a search routine where undefined and zero are both valid results. I'm returning a two element array like ($result, $answer)
because I don't have an "undefined but true" value. It works fine but is a bit klutzy. A class seems like overkill.
Does such a thing exist or can be faked somehow? I'm thinking of things like the 0E0
trick, etc.
More details. This is the user interface I would like. The current routine returns two values, the result (whether or not the key was found) and a value if it was.
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";
}
You could just return a reference to the result. Return undef
for no result, \( undef )
for literal undefined result, \( whatever )
for any other result. Then the caller can just use $$result
(after making sure $result
is defined).
No, but there are numerous ways you can return three states.
Solution 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";
}
List assignment in scalar context evaluates to the number of elements returned by its right-hand side.
Solution 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";
}
Solution 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";
}
Solution 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";
}
BTW, I would pass the data structure as the first parameter and the key as the second parameter. More like OO programming.
You might return your answer in a list (not an array): empty list for no results found, and a one element list otherwise ((undef,)
or ($some_answer,)
).
It's still rather klunky, but:
if (my ($answer) = the_function()) { # note parentheses
process_answer($answer); # might be undef, false, etc.
} else {
no_results_found();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With