Error Indications
If you want your function to return in such a way that the caller will
realize there’s been an error, the most natural way to do this in
Perl is to use a bare return
statement without an argument. That way when the function is used in
scalar context, the caller gets undef; when used in list context, the
caller gets a null list.
Under extraordinary circumstances, you might choose to raise
an exception to indicate an error. Use this measure sparingly,
though; otherwise, your whole program will be littered with
exception handlers. For example, failing to open a file in a generic
file-opening function is hardly an exceptional event. However,
ignoring that failure might well be. The wantarray built-in returns undef if your function was called in void
context, so you can tell if you’re being ignored:
if ($something_went_awry) {
return if defined wantarray; # good, not void context.
die "Pay attention to my error, you danglesocket!!!\n";
}Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access