What is the most common/idiomatic way to define partial functions in Perl, that is functions that are not defined on all inputs. For example, in Haskell we have
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (x:xs) = Just x
in C we have
int factorial(int n) {
assert(n >= 0);
int result = 1;
while (n) result *= n--;
return result;
}
or
int factorial(int n) {
if (n < 0) return -1;
int result = 1;
while (n) result *= n--;
return result;
}
I would rather not import a CPAN module.
Like in C, you can return from the middle of Perl subs.
Assertion-style:
If I were to use
returnhere, I'd probably returnundefrather than-1. Any misuse of this returned value should be noisy.But I would more likely throw an exception (using
croak) for invalid inputs.A side note on how to check for different return values.
ifconditionreturn false;return 0;return "";return "0";return undef;return;my $x = f()defined( my $x = f() )my ( $x ) = f()