|Keep It Simple, Stupid|
Re: Re: Re: Re: What should be returned in scalar context? (best practice)by Juerd (Abbot)
|on Dec 21, 2003 at 19:38 UTC||Need Help??|
Read the code: return @ret; . . . it says "return" and is followed by an array.
print @foo; does not print an array, it prints a list.
More importantly, it behaves like an array.
Only in two ways. It returns a number of elements in scalar context and a list of elements in list context. That's where the comparison ends.
It is not an array. Don't call it an array, because it simply is not an array. You say it behaves like an array, but it does not. The very things that make an array an array do not apply. Just some context sensitivity, but that does not make your list or number an array.
If you don't want to call it a list because in scalar context it returns a number of elements, specify both behaviours in your documentation. That's what perl's documentation also does. See grep, keys, split, etcetera.
"Returns a list" is wrong when the sub is called in scalar context. "Returns an array" is wrong in every possible context. Note that "array context" does exist and your sub cannot be used in it.
Only an lvalue sub can return an array, but that cannot be done using the return keyword.
It doesn't behave like a list literal
Indeed. It does not behave like a list *literal*. But in list context, it does behave like a list, in every single way. It's important to know that there are two kinds of lists, and that list literals are special with syntax; other than that, they're just lists.
Documenting that it returns an array is the only clear way to describe its behavior.
No, no, no, no, NO! It's the most vague way to describe its behaviour. Don't call it clear, because it is the very opposite of clear! If you want to be absolutely clear, you must specify the difference in behaviour for every context, or modify the sub so that it really does behave like an array, or like a list.
"Array" and "array reference" are not synonyms.
Correct. But why do you think that "list" and "array" are synonyms? They're not. My point is not that "returns an array" would imply it being a reference. My point is that it's entirely unclear whether it returns a list or a reference to an array. It's not returning an array, that's for sure (since you use the return keyword, we're not talking about an lvalue sub here).
If you sometimes describe a reference to an array as "an array", then you are being sloppy and you should stop.
I could not agree more.
I'd like to add this one: