ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы.



10.6. 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)


Previous: 10.5. Passing Arrays and Hashes by ReferencePerl CookbookNext: 10.7. Passing by Named Parameter
10.5. Passing Arrays and Hashes by ReferenceBook Index10.7. Passing by Named Parameter