如何在Perl中测试"某些东西"是否为哈希?

SDG*_*tor 25 perl

我从另一个函数接收哈希哈希,哈希哈希的一些元素可以是另一个哈希.我如何测试以查看某些内容是否为哈希?

Cha*_*ens 40

根据您的需要,您需要使用refreftype(在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";
}
Run Code Online (Sandbox Code Playgroud)

  • @brian d foy你不熟悉"tf"这个词吗?这就像"如果",但更是如此. (3认同)
  • 我认为**强调**如果**是"iiiif",或者perlishly:''i'x $ n.'f'`($ n> 1) (2认同)

Iva*_*uev 15

使用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}
Run Code Online (Sandbox Code Playgroud)

  • 我不认为违反对象封装是一个好主意. (6认同)
  • 此测试不适用于类似哈希的对象:`$ r = {};祝福$ r,"失败";打印ref $ r` (2认同)

Joe*_*Joe 5

我一直在使用isa,但如果被测试的东西不是对象(或者可能不是对象),则需要将其称为函数UNIVERSAL::isa:

if ( UNIVERSAL::isa( $var, 'HASH' ) ) { ... }
Run Code Online (Sandbox Code Playgroud)