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


in reply to Thoughts on "one function, flexible arguments"?

Possibly easy to maintain AND flexible parameters:
use strict; use warnings; sub my_func { my %params; my $fix_dispatcher = { HASH => sub{ %params = %{$_[0]}}, ARRAY => sub{ %params = @{$_[0]}}, SCALAR => sub{ $params{message} = ${$_[0]}}, _DIRECT_SCALAR=> sub{ $params{message} = $_[0]}, _DIRECT_ARRAY => sub{ %params = @_}, }; my $param_type = scalar(@_)> 1 ? '_DIRECT_ARRAY' : ref $_[0] || '_DIRECT_SCALAR'; $fix_dispatcher->{$param_type}->(@_); print "Message received: " . $params{message}; if ($params{newline}) { print "\n" } } # good my_func( { message => "Hello, world! (hashref)", newline=>1 } ); # also good my_func( message => "Hello, world! (hash)" ,newline=>1); my_func( "Hello, world! (Scalar)" ); print("\n"); my_func(\"Hello, world! (Scalar Ref)" ); print("\n"); my_func( "message" , "Hello, world! (array)", "newline",1 ); my_func( ["message" , "Hello, world! (array ref)", "newline",1 ]);
UPDATE1: Added "array ref" call.
UPDATE2: Deleted unnecessary variable "$fix_subref".

                "From there to here, from here to there, funny things are everywhere." -- Dr. Seuss