in reply to Context aware functions - best practices?
If I understand you correctly, you only want to return a scalar from this function if it is called with only one argument. What I'm thinking of is a function that, when called with one argument returns a scalar and when called with multiple arguments returns an array. Then you could just have sth like this:
It depends on what your function is doing. The problem with the wantarray solution is that you are calculating an array of results but not giving everything back to the user - whether you return the first or the last element, it's lying, because you actually had more results calculated in the sub.sub foo { my @args = @_; # do your calculation if (@args != 1) { return @results; } else { return $results[0]; # or return $result; # depending on your calculation } }
What I'm trying to say: the user is normally expecting an array returned from that sub. So he might on purpose write sth like my $length = foo(1,2,3); to get the amount of results. This user might then be surprised if he gets the first (or last) element of the array instead. If you return the whole array then he could still choose the get only the first (or last value) or any value in between like so:my $value = ( foo(1,2,3) )[$i];
Just a few thoughts ...
-- Hofmator
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Context aware functions - best practices?
by Aristotle (Chancellor) on Jan 14, 2003 at 23:39 UTC |
In Section
Seekers of Perl Wisdom