http://www.perlmonks.org?node_id=26334


in reply to (Slice 'em and Dice 'em) RE: Arrays are not lists
in thread Arrays are not lists

Another approach is to be specific. If you want to return a list of items, and your invocation makes no sense in a scalar context, say so:
sub this_returns_a_list_only { wantarray or die "DURN IT, USE ME IN A LIST CONTEXT!"; ... ... }
If you code like that, you can safely add all the return expressions you want, knowing they will be always invoked in a list context.

There is no "proper" relationship between what a function returns in a list context and what it returns in a scalar context. There's only the relationship that makes sense for the domain in which the function returns.

For example, it makes perfect sense to me that sortalways returns undef in a scalar context. What one single value would make sense to be returned otherwise? And that wonderful getpwnam, which returns a 9-element list in a list context, or just the most useful part of that (the second element, the user id number) in a scalar context.

And finally, the localtime,gmtime twins. Very cool that the scalar context definition is completely unrelated to the list context definition.

So, perhaps you can stop thinking of "what one expression makes sense to return" and think instead of "what do I want this subroutine to return in a list context vs. a scalar context?" and write your code appropriately. That's why wantarray is in there!

-- Randal L. Schwartz, Perl hacker