Recipe 10.10. Returning Failure (Perl Cookbook)

Perl Cookbook

Perl CookbookSearch this book
Previous: 10.9. Returning More Than One Array or HashChapter 10
Subroutines
Next: 10.11. Prototyping Functions
 

10.10. Returning Failure

Problem

You want to return a value indicating that your function failed.

Solution

Use a bare return statement without any argument, which returns undef in scalar context and the empty list () in list context.

return;

Discussion

A return without an argument means:

sub empty_retval {
    return ( wantarray ? () : undef );
}

You can't use just return undef because in list context you will get a list of one value: undef. If your caller says:

if (@a = yourfunc()) { ... }

Then the "error" condition will be perceived as true, because @a will be assigned (undef) and then evaluated in scalar context. This yields 1, the number of elements in @a, which is true. You could use the wantarray function to see what context you were called in, but a bare return is a clear and tidy solution that always works:

unless ($a = sfunc()) { die "sfunc failed" }
unless (@a = afunc()) { die "afunc failed" }
unless (%a = hfunc()) { die "hfunc failed" }

Some of Perl's built-in functions have a peculiar return value. Both fcntl and ioctl have the curious habit of returning the string "0 but true" in some circumstances. (This magic string is conveniently exempt from the -w flag's incessant numerical conversion warnings.) This has the advantage of letting you write code like this:

ioctl(....) or die "can't ioctl: $!";

That way, code doesn't have to check for a defined zero as distinct from the undefined value, as it would for the read or glob functions. "0 but true" is zero when used numerically. It's rare that this kind of return value is needed. A more common (and spectacular) way to indicate failure in a function is to raise an exception, as described in Recipe 10.12.

See Also

The undef, wantarray, and return functions in Chapter 3 of Programming Perl and perlfunc (1); Recipe 10.12


Previous: 10.9. Returning More Than One Array or HashPerl CookbookNext: 10.11. Prototyping Functions
10.9. Returning More Than One Array or HashBook Index10.11. Prototyping Functions

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.