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


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

Replies are listed 'Best First'.
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.