There is no ambiguity here, and you cannot unconditionally return the list.
In Perl 5, every expression, including a subroutine call, has a context that is either a list context (returning zero or more values) or a scalar context (returning exactly one value). The return extends the context of a subroutine call to the expression in the return expression. Suppose you are trying to return a list with several elements:
return (6, 7, 8);
This is not guaranteed to be a list. If sub is called in a scalar context, then the comma expression in the return expression is also in the scalar context, and the behavior of the comma expression in the scalar context is to return the rightmost value here 8 .
If you used a temporary array,
return @{[6, 7, 8]}
then, if it is called in a scalar context, you will get the behavior of arrays in a scalar context, which should return the number of elements in the array.
All of the above applies to single-item lists, as does the three-item list in the example.
Some general facts:
It is not possible to force a return list — you can only return what the caller requests.
There is no system choice for what happens if you call list-y in a scalar context - the number of items in the list to be returned in the context of the list is a common choice, but not universal.
If you want to have a well-defined routine, you cannot say that "it always returns a list"; you must specify what happens when you need to return a scalar. (You could decide that he will always die if you want.)
If you want to make an explicit choice based on whether the call is in a scalar or context list, you can use the weakly named builtin wantarray , which returns true if the subroutine was called in the context of the list.
This is the closest to what you requested, which really exists. Please note: there are no brackets - the brackets do not affect the context.
die "can't be scalar" unless wantarray; return 6;
source share