|Syntactic Confectionery Delight|
Re: Re: Context aware functions - best practices?by MarkM (Curate)
|on Jan 15, 2003 at 07:17 UTC||Need Help??|
Regarding the choice to use wantarray to grant context to the return value of a subroutine, you say:
Consequently, in most cases, I think that if a user wants to call a function that is documented to return a list and assign it directly to a scalar, it is fair to ask him to remember what he is doing.
An argument against this is that the user expects a list to be returned, not an array. Normally when a list is used on the right side of the expression, a scalar on the left side of the expression will be given the last value in the list, not the number of items in the list. This argument at least indicates that wantarray is desirable, and that the other suggestion in this thread (returning the last item in the list) is preferable to returning the array itself.
Further on, you suggest that:my $x = (foo(l));
Is preferable to:my ($x) = foo(1);
In Perl, there is a clear precidence for context to be significant. Consequently, Perl programmers expect functions to return the most sensible results in either context. It is a question of programming efficiency, more than programming purity. Calling a function in scalar context is like using a contraction in the English language. "I want the simpler form."
Often, the value in scalar context is _very_ different than than the value in list context. For example, the builtin getpwnam() functions returns the username in scalar context, while getpwuid() returns the uid. Both return the same sort of list in list context.
In terms of intuition, most people intuitively expect the following two expressions to be equivalent:my($x) = foo(...);
And:my $x = foo(...);
Sometimes the above is not the case, however, the times that this is not the case are usually the exception to the rule, and not the rule itself.
I, personally, often use "wantarray ? @array : $array" as a return value, not only because I believe that this is the most intuitive behaviour, but also because in most cases, I consider this the most useful behaviour. Useful often directly equates to efficient from a programming perspective.