How can I test that "something" is a hash in Perl?

I am receiving a hash of hashes from another function, and some elements of the hash of hashes can be another hash. How can I test to see if something is a hash?

Answers


Depending on what you want you will need to use ref or reftype (which is in Scalar::Util, a core module). If the reference is an object, ref will return the class of the object instead of the underlying reference type, reftype will always return the underlying reference type.

if (ref $var eq ref {}) {
   print "$var is a hash\n";
}

use Scalar::Util qw/reftype/;

if (reftype $var eq reftype {}) {
    print "$var is a hash\n";
}

Use ref function:

ref($hash_ref) eq 'HASH' ## $hash_ref is reference to hash
ref($array_ref) eq 'ARRAY' ## $array_ref is reference to array

ref( $hash{$key} ) eq 'HASH' ## there is reference to hash in $hash{$key}

I've always used isa, but if the thing being tested isn't an object (or might not be an object), you need to call it as the function UNIVERSAL::isa :

if ( UNIVERSAL::isa( $var, 'HASH' ) ) { ... }

use Params::Util qw<_HASH _HASH0 _HASHLIKE>;

# for an unblessed hash with data
print "$ref is a hash\n" if _HASH( $ref ); 
# for an unblessed hash empty or not
print "$ref is a hash\n" if _HASH0( $ref ); 
# for a blessed hash OR some object that responds as a hash*
print "$ref is hashlike\n" if _HASHLIKE( $ref );

* through overload

You probably do not need the last one, though.

see Params::Util


Need Your Help

C / C++ How to copy a multidimensional char array without nested loops?

c++ c arrays multidimensional-array char

I'm looking for a smart way to copy a multidimensional char array to a new destination. I want to duplicate the char array because I want to edit the content without changing the source array.