Recipe 10.10 Returning Failure

10.10.1 Problem

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

10.10.2 Solution

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

return;

10.10.3 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 assigned to @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 nagging warnings about improper numerical conversions.) 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.

10.10.4 See Also

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



Perl Cookbook
Perl Cookbook, Second Edition
ISBN: 0596003137
EAN: 2147483647
Year: 2003
Pages: 501

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net