【Perl學習筆記】1.perl的ref 函數

perl有引用的概念:一組數據其實是另外一組數據的引用。這些引用稱爲指針,第一組數據中存放的是第二組數據的頭地址。引用的方式被用得至關廣泛,特別是在面向對象的模塊、函數的參數傳遞等常見。但perl對每一個引用都是以一個普通的變量來定義的,有時候,若是數據的架構比較複雜,咱們可能會困惑於某個變量所指向的地址的實際內容是什麼?perl的ref函數就能夠幫助咱們。架構


1、說明
從perl自帶的幫助說明能夠了解相關的用法:less

引用
$ perldoc -tf ref
ref EXPR
ref     Returns a non-empty string if EXPR is a reference, the empty
        string otherwise. If EXPR is not specified, $_ will be used. The
        value returned depends on the type of thing the reference is a
        reference to. Builtin types include:

            SCALAR
            ARRAY
            HASH
            CODE
            REF
            GLOB
            LVALUE

        If the referenced object has been blessed into a package, then
        that package name is returned instead. You can think of "ref" as
        a "typeof" operator.

            if (ref($r) eq "HASH") {
                print "r is a reference to a hash./n";
            }
            unless (ref($r)) {
                print "r is not a reference at all./n";
            }

        See also perlref.

2、舉例
簡單來講,就是若是一個變量是個引用,那ref就能夠返回一個表示其實際引用對象的描述性字符串,不然就會返回空值。若是沒有指定ref函數的參數,默認對$_變量操做。若是被引用的對象已經被打包,則會返回該包的名稱,相似typeof操做符。
代碼:

#!/usr/bin/perl -w
%hash=('Tom'=>'Male','Jerry'=>'Female');
$href=/%hash;
for $key (keys %$href) {
  print $key." is ".$href->{$key};
  print "/n";
}
if ( ref($href) eq "HASH" ) {
  print "href is a reference to a hash./n";
}
unless ( ref($href) ) {
  print "href is not a reference at all./n";
}
print "href is ",ref($href),"./n";

輸出結果:
引用
$ perl testref.pl Jerry is Female Tom is Male href is a reference to a hash. href is HASH
相關文章
相關標籤/搜索