I strongly dislike return wantarray ? @ret : \@ret;. The justification that it offers performance benefits for those who want them reeks of premature optimization; if it turns out to be necessary, I'll have the function always return a reference. If it's not necessary, having the function set up this way anyway makes it inconvenient to deal with cases where the result list is expected to have only a single element. It also leads to a conundrum when the array is empty; some people will want to be able to dereference the return value without checking for undef, while others will want the scalar context return value to sensibly work as a boolean. It just doesn't work out; I would never consider this style in any case.

I tend to return @ret[ 0 .. $#ret ]; these days and find it to be completely unsurprising most of the time. It is hardly a rule though, and I may do other things on other occasions.

When we're talking about methods rather than plain functions, and the returned list consists of objects, an iterator object is a helpful option. A particularly nice kind of iterator object relays certain method calls to all of its contained list's objects, so that you can do something like $family->children->sleep(); and have all the children collectively leave for bed.


sub foo { if (1 != @_) { return map foo($_), @_; } # body of foo here. return $whatever; }
This seems to indicate a 1:1 mapping. In that case I offer
sub foo { ( map { # body of foo here. } @_ )[ 0 .. $#_ ]; }

Makeshifts last the longest.


In reply to Re: What should be returned in scalar context? by Aristotle
in thread What should be returned in scalar context? by tilly

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.