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

hornpipe2 has asked for the wisdom of the Perl Monks concerning the following question:

Suppose I have a subroutine which expects a hash reference, containing named parameters. The simple way to write this is:
sub my_func { my $params = shift; print "Message received: " . $params->{message}; if ($params->{newline}) { print "\n" } } # good my_func( { message => "Hello, world!" } ); # "Error: Not a Hash reference" my_func( message => "Hello, world!" );
But there is a more "liberal" way to write this, which accepts the parameters in a variety of presentations (list, list-ified hash, scalar for a single "most important" param, etc):
sub my_func { my %params; if (ref($_[0]) eq 'HASH') { %params = %{+shift}; } elsif (ref($_[0]) eq 'ARRAY') { (%params) = @{+shift}; } elsif (ref($_[0]) eq 'SCALAR') { $params{message} = ${+shift}; } elsif (scalar @_ > 1) { (%params) = @_; } else { $params{message} = shift; } print "Message received: " . $params{message}; if ($params{newline}) { print "\n" } } # good my_func( { message => "Hello, world!" } ); # also good my_func( message => "Hello, world!" );
What are the community's thoughts on this pattern? Is this easier for users, and is the trade-off worthwhile for the maintainer?