我从另一个函数接收到哈希的哈希,其中一些元素可能是另一个哈希。我如何测试某个元素是否为哈希?
我从另一个函数接收到哈希的哈希,其中一些元素可能是另一个哈希。我如何测试某个元素是否为哈希?
根据你的需要,你需要使用 ref
或者是 reftype
(位于核心模块Scalar::Util
中)。如果引用是一个对象,ref
会返回该对象的类而不是底层引用类型,reftype
总是会返回底层引用类型。
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";
}
'i'x$n.'f'
(当$n > 1时)。 - Mike Ellery使用ref
函数:
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}
$r = {}; bless $r, "fail"; print ref $r
- mob$array = []; bless $array, 'HASH'; print ref $array;
打印出 HASH
。不过你永远都不应该这样做。 - Greg Nisbet我一直使用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 );
* 通过overload
实现
最后一个可能不需要。
Params::Util::_HASHLIKE
调用 Scalar::Util::reftype
,但它还检查其参数是否重载了哈希解引用运算符——这可以检测到那些即使不是真正的哈希引用也可以假装成哈希引用的对象。 - mob