Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Check whether a variable is a hash or not

by imp (Priest)
on Feb 15, 2007 at 17:15 UTC ( #600250=note: print w/ replies, xml ) Need Help??


in reply to Check whether a variable is a hash or not

You can almost always use either ref or Scalar::Util's reftype, as mentioned by the other monks. The only time that approach would fail is when the object being tested acts like a hash using the magic of overload. In those rare cases the only solution I know is to try and use it like a hash.

{ package fakehash; use overload "%{}" => sub { return {1 => 2} }; sub new {my $c; bless \$c}; } use strict; use warnings; use Scalar::Util qw( reftype ); my $fake = fakehash->new; printf "fake is ref %s\n", ref $fake; printf "fake is reftype %s\n", reftype $fake; # Try to use $fake as a hashref. # The return value of eval should be 1 if the first # statement is successful, as 1 is the last statement executed # in the block # The assignment to (undef) is to avoid this warning: # "Useless use of a variable in void context" if ( eval {(undef) = %$fake; 1}) { print "fake is pretending to be a hashref\n"; }


Comment on Re: Check whether a variable is a hash or not
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2014-09-01 14:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (13 votes), past polls