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

Re: Function that accepts both hashes/arrays and hashrefs/arreyrefs

by jandrew (Hermit)
on Jun 19, 2009 at 16:45 UTC ( #773079=note: print w/ replies, xml ) Need Help??


in reply to Function that accepts both hashes/arrays and hashrefs/arreyrefs

As mentioned by others the risk of sending an array or a hash to a function is risky with lots of unexpected things possible see: perlsub. However if you will limit yourself to only array refs or hash refs then the real question is how to disinguish which one was sent and what to do with it. I like;

my $Input = $ArrayRef || $HashRef; set_value( $Input ); sub set_value { #recieve the passed variable(s) #my $self = shift;#For OO subs my $Arg = shift; if ( ref $Arg eq 'HASH' ) { ### Handle a hash $Arg->{key} } elsif ( ref $Arg eq 'ARRAY' ) { ### Handle an array $Arg->[$index] } else { ### Must not be an array ref or hash ref } }
Updated code block
Cleaner syntax, Thank you Porculus


Comment on Re: Function that accepts both hashes/arrays and hashrefs/arreyrefs
Download Code
Re^2: Function that accepts both hashes/arrays and hashrefs/arreyrefs
by Porculus (Hermit) on Jun 19, 2009 at 18:38 UTC

    That's not a great way to do it; your code will, for example, think it's got an array reference if someone passes the string "This is NOT an array(really!)" as an argument.

    A better approach is to use the ref function.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2014-04-17 01:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (437 votes), past polls