If the method only ever returns a single scalar, then returning undef is better than returning an empty list. Each has its pitfalls. Sure, undef in a list assignment in a Boolean context isn't false. But an empty list as part of lots of constructs where a single scalar is expected leads to surprises that are at least as bad.

For subs that at some other point can return more than one item, then I agree that one should return an empty list to indicate "failure" not undef. For subs that in all other cases return a single scalar, it is better to return undef than to transform your function into something that returns a single scalar except in the case of failure.

I've yet to see what I would consider reasonable code that demonstrates using a function that always returns a single scalar in a list assignment and using that list assignment in a Boolean context and expecting failure to be indicated. So for such functions, the theorized risk from returning undef is nearly zero.

But I've seen lots of people bitten by functions returning an empty list when what they expected was a single scalar that might be undef. This problem happens for any inclusion of such in a list like an array or hash initialization, a call to almost any function (including things like push), etc. I find such code rather frequent and reasonable so I think mitigating this risk is much more important.

- tye        


In reply to Re^2: getting 2 things done at once with Class::Base (return undef) by tye
in thread getting 2 things done at once with Class::Base by princepawn

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.