http://www.perlmonks.org?node_id=226953


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:
sub foo { my @args = @_; # do your calculation if (@args != 1) { return @results; } else { return $results[0]; # or return $result; # depending on your calculation } }
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.

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
    I'm not calculating all that much. As I've said repeatedly, what I want is merely a convenience feature to have the same convenience as CGI offers with my $foo = $cgi->param(''); vs my ($foo) = $cgi->param(''); which both do the same.

    Data getting thrown away is not really a problem here, just like when doing my $foo = (bar(), baz(), qux()); the user knows he asked for more than he provided the space to save it in.

    Makeshifts last the longest.