Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Thoughts on "one function, flexible arguments"?

by NetWallah (Canon)
on Aug 28, 2019 at 23:40 UTC ( #11105198=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11105198]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2020-11-26 21:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?