有时候可能会须要检查引用是什么类型的,省得咱们期待是一个数组引用,却给了一个hash引用。数组
ref函数能够用来检查引用的类型,并返回类型。perl中内置了以下几种引用类型,若是检查的不是引用,则返回undef。less
SCALAR ARRAY HASH CODE REF GLOB LVALUE FORMAT IO VSTRING Regexp
例如:函数
@name=qw(longshuai xiaofang wugui tuner); $ref_name=\@name; %myhash=( longshuai => "18012345678", xiaofang => "17012345678", wugui => "16012345678", tuner => "15012345678" ); $ref_myhash =\%myhash; print ref $ref_name; # ARRAY print ref $ref_myhash; # HASH
因而,能够对传入的引用进行判断:ui
my $ref_type=ref $ref_hash; print "the expect reference is HASH" unless $ref_type eq 'HASH';
上面的判断方式中,是将HASH字符串硬编码到代码中的。若是不想硬编码,能够让ref对空hash、空数组等进行检测,而后对比。编码
ref [] # 返回ARRAY ref {} # 返回HASH
之因此能够对它们进行检测,是由于它们是匿名数组、匿名hash引用,只不过构造出的这些匿名引用里没有元素而已。也就是说,它们是空的匿名引用。code
例如:对象
my $ref_type=ref $ref_hash; print "the expect reference is HASH" unless $ref_type eq ref {};
或者,将HASH、ARRAY这样的类型定义成常量:字符串
use constant HASH => ref {}; use constant ARRAY => ref []; print "the expect reference is HASH" unless $ref_type eq HASH; print "the expect reference is ARRAY" unless $ref_type eq ARRAY;
除此以外,Scalar::Util
模块提供的reftype函数也用来检测类型,它还适用于对象相关的检测。hash