有时候可能会需要检查引用是什么类型的,免得我们期待是一个数组引用,却给了一个hash引用。

ref函数可以用来检查引用的类型,并返回类型。perl中内置了如下几种引用类型,如果检查的不是引用,则返回undef。

    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

于是,可以对传入的引用进行判断:

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引用,只不过构造出的这些匿名引用里没有元素而已。也就是说,它们是空的匿名引用。

例如:

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函数也用来检测类型,它还适用于对象相关的检测。

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!