10.6. Detecting Return ContextProblemYou 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 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 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
|
|