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


In reply to Re: most appropriate return data type by pileofrogs
in thread most appropriate return data type by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.