Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: most appropriate return data type

by pileofrogs (Priest)
on Feb 19, 2010 at 18:13 UTC ( [id://824223]=note: print w/replies, xml ) Need Help??


in reply to most appropriate return data type

I think wantarray isn't really what the OP wants. He/She wants to know the best way to deal with a function that may return 0, 1 or more answers. Wantarray is helpful for those times when you know you only want one value. I think the OP has a situation where there is usually only 0 or 1 answer, but sometimes more than 1.

For example, if I'm writing a function that returns the name of the hat I'm wearing. The answer is either a name or no name. Suddenly, I realise I sometimes wear more than one hat! Sometimes I wear a lot of hats! How should I write my function? Should I return a scalar when I have zero or one hat, or should I return a list even when I have one or no hats?

The choices are generally to either check what you get from the function or always use a list/array. I generally* agree that it's best to always return a list (or list ref). If you're going to write the stuff to handle a list anyway, you're just adding extra work by writing special stuff to handle scalars. It's also more robust and it scales better. By scales better, I mean, in that one instance where you always get a scalar, you suddenly realise you want a list and you have to rewite a ton of stuff with lots of trickling expectations. Lastly, if you do decide in some special case that you want to deal with a single value differently, it's easy.

Maybe I'm totally wrong about what the OP means though...

* generally folks, I said generally!

--Pileofrogs

Log In?
Username:
Password:

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

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

    No recent polls found