简体   繁体   中英

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?

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}

我一直使用isa ,但如果被测试的东西不是对象(或者可能不是对象),则需要将其称为函数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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM