Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: What should be returned in scalar context?

by Aristotle (Chancellor)
on Dec 03, 2003 at 07:08 UTC ( [id://311848]=note: print w/replies, xml ) Need Help??


in reply to What should be returned in scalar context?

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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (6)
As of 2024-04-18 06:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found