Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

returning lists and scalars

by merlyn (Sage)
on Aug 05, 2000 at 17:52 UTC ( [id://26334]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://26334]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2024-04-19 23:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found