zoukankan      html  css  js  c++  java
  • Perl检查引用类型

    有时候可能会需要检查引用是什么类型的,免得我们期待是一个数组引用,却给了一个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函数也用来检测类型,它还适用于对象相关的检测。

  • 相关阅读:
    numpy模块
    Flask--请求扩展
    Flask补充--threading.local对象
    Flask-Cookies和Session
    Flask--请求上下文
    SQL Server 2005详细安装过程及配置
    Linux设置Mysql开机自启动服务
    重启网卡提示Bringing up interface eth0:
    本地docker容器迁移到服务端
    Window安装tomcat环境
  • 原文地址:https://www.cnblogs.com/f-ck-need-u/p/9713851.html
Copyright © 2011-2022 走看看