Perl檢查引用類型

有時候可能會須要檢查引用是什麼類型的,省得咱們期待是一個數組引用,卻給了一個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

相關文章
相關標籤/搜索