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?? |
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. This seems to indicate a 1:1 mapping. In that case I offer
Makeshifts last the longest.
In Section
Meditations
|
|