Perl is a language with pronounced context sensitivity: the result of an expression depends on how its result is used. Historically, this has made the language extraordinarily flexible, but even experienced developers can make mistakes if they do not consider the peculiarities of scalar and list contexts.
The question arose from the early versions of Perl when it was assumed that the same operation could return either an array or a single value — for example, the call to the localtime function can return either a list or a string depending on the situation.
The problem is that improper context handling leads to unexpected errors: for example, extra elements, empty results, or strange behavior in logical expressions.
The solution is to always clearly understand in what context a function or expression is called, use the built-in function wantarray in your subroutines, and avoid implicit mixing of contexts.
Code example:
sub may_return { return wantarray ? (1, 2, 3) : "scalar result"; } my @arr = may_return(); # will return (1,2,3) my $val = may_return(); # will return "scalar result"
Key features:
Can you determine if an expression is used in void context within the function itself?
Answer: No, only scalar or list. In Perl 5, there is no function to determine void context within a subroutine — the wantarray function returns undef in this case, but for different behavior.
Code example:
sub example { return wantarray ? (1,2) : wantarray ? undef : "scalar"; # incorrect }
Can a function return different data types depending on the context?
Answer: Yes, this is completely permissible and often used.
Does the behavior of operators (e.g., shift, pop) depend on context?
Answer: Yes. For example, when shift is called within a function — it depends on whether @_ (globally or lexically) is used, and whether the result will be passed as a scalar or as a list.
A developer wrote a function that always returns a list, not considering scalar context. If this function is called in scalar context, only the last element of the list will be obtained.
Pros:
Cons:
The function uses wantarray and returns either a list or a meaningful scalar or undef.
Pros:
Cons: