[Omaha.pm] The many faces of return;

Andy Lester andy at petdance.com
Wed Sep 3 10:42:20 PDT 2008


On Sep 3, 2008, at 12:11 PM, Jay Hannah wrote:

> I got hung up on "return false" today. Apparently "return false" is  
> common lingo for   return;   or   return ();    which are both  
> guaranteed to be false in scalar or array context. As opposed to    
> return undef;   or   return 0;   which are false in scalar context,  
> but true in array context.


That's one of the things that Perl::Critic catches.  If you want to  
return failure or nothing, just use "return".  See Perl Best Practices  
for details, or this page:

http://search.cpan.org/dist/Perl-Critic/lib/Perl/Critic/Policy/Subroutines/ProhibitExplicitReturnUndef.pm

Returning undef upon failure from a subroutine is pretty common. But  
if the subroutine is called in list context, an explicit return undef;  
statement will return a one-element list containing (undef). Now if  
that list is subsequently put in a boolean context to test for  
failure, then it evaluates to true. But you probably wanted it to be  
false.

   sub read_file {
       my $file = shift;
       -f $file || return undef;  #file doesn't exist!

       #Continue reading file...
   }

   #and later...

   if ( my @data = read_file($filename) ){

       # if $filename doesn't exist,
       # @data will be (undef),
       # but I'll still be in here!

       process(@data);
   }
   else{

       # This is my error handling code.
       # I probably want to be in here
       # if $filname doesn't exist.

       die "$filename not found";
   }

The solution is to just use a bare return statement whenever you want  
to return failure. In list context, Perl will then give you an empty  
list (which is false), and undef in scalar context (which is also  
false).

   sub read_file {
       my $file = shift;
       -f $file || return;  #DWIM!

       #Continue reading file...
   }

xoxo,
Andy

--
Andy Lester => andy at petdance.com => www.petdance.com => AIM:petdance





More information about the Omaha-pm mailing list