home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Perl CookbookPerl CookbookSearch this book

10.6. Detecting Return Context

10.6.3. Discussion

Many built-in functions act differently when called in scalar context than they do when called in list context. A user-defined function can learn which context it was called in by checking wantarray. List context is indicated by a true return value. If wantarray returns a value that is false but defined, then the function's return value will be used in scalar context. If wantarray returns undef, your function isn't being asked to provide any value at all.

if (wantarray( )) {
    print "In list context\n";
    return @many_things;
} elsif (defined wantarray( )) {
    print "In scalar context\n";
    return $one_thing;
} else {
    print "In void context\n";
    return;  # nothing
}

mysub( );                    # void context

$a = mysub( );               # scalar context
if (mysub( )) {  }           # scalar context

@a = mysub( );               # list context
print mysub( );              # list context

10.6.4. See Also

The return and wantarray functions in Chapter 29 of Programming Perl and in perlfunc(1)



Library Navigation Links

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