Detecting Return Context

Problem

You want to know whether your function was called in scalar context or list context. This lets you have one function that does different things, like most of Perl’s built-in functions.

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
}

Discussion

Many built-in functions act differently when called in scalar context than in list context. A user-defined function can learn the context it was called in by examining the return value from the wantarray built-in. List context is indicated by a true return value. If it returns a value that is false but defined, then the function’s return value will be used in scalar context. If it returns undef, it isn’t being asked to provide a 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
               
               
               
               

See Also

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

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.