Perl CookbookPerl CookbookSearch this book

10.6. Detecting Return Context

10.6.1. Problem

You want to know in which context your function was called. This lets one function do different things, depending on how its return value or values are used, just like many of Perl's built-in functions.

10.6.2. Solution

Use the wantarray( ) function, which has three possible return values, depending on how the current function was called:

if (wantarray( )) {
    # list context
}
elsif (defined wantarray( )) {
    # scalar context
}
else {
    # void 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.