![]() |
|
We don't bite newbies here... much | |
PerlMonks |
returning lists and scalarsby merlyn (Sage) |
on Aug 05, 2000 at 17:52 UTC ( #26334=note: print w/replies, xml ) | Need Help?? |
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:
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
In Section
Meditations
|
|