[Omaha.pm] The many faces of return;

Jay Hannah jay at jays.net
Wed Sep 3 10:11:12 PDT 2008


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.

Fun, huh?   :)

j




$ cat perl_return_and_context.t
use Test::More tests => 8;

foreach my $sub (qw(
    return_0 return_undef return_empty_list return_semi_colon
)) {
    my $ret = &$sub();
    ok(! $ret,       "$sub in scalar context");
    my @ret = &$sub();
    ok(! @ret,       "$sub in array context");
    &$sub();
}

sub return_0 {
    #print_context(wantarray);
    return 0;
}
sub return_undef {
    #print_context(wantarray);
    return undef;
}
sub return_empty_list {
    #print_context(wantarray);
    return ();
}
sub return_semi_colon {
    #print_context(wantarray);
    return;
}


sub print_context {
    my ($wantarray) = @_;
    if (not defined $wantarray) {
       print "[void]";
    } elsif ($wantarray) {
       print "[list]";
    } else {
       print "[scalar]";
    }
}


$ perl perl_return_and_context.t
1..8
ok 1 - return_0 in scalar context
not ok 2 - return_0 in array context
#   Failed test 'return_0 in array context'
#   at perl_return_and_context.t line 9.
ok 3 - return_undef in scalar context
not ok 4 - return_undef in array context
#   Failed test 'return_undef in array context'
#   at perl_return_and_context.t line 9.
ok 5 - return_empty_list in scalar context
ok 6 - return_empty_list in array context
ok 7 - return_semi_colon in scalar context
ok 8 - return_semi_colon in array context
# Looks like you failed 2 tests of 8.



More information about the Omaha-pm mailing list