曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 4404|回复: 0
打印 上一主题 下一主题

ref -- 判断引用是否存在并返回引用指向的数据类型

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34387
跳转到指定楼层
楼主
发表于 2011-10-25 20:50:46 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
ref 函数可以用来判断引用是否存在。如果它的参数是一个指针(引用)变量,那么 ref 就返回该引用指向的数据类型。比如指针指向的是标量,那么返回 SCALAR;又如指向的是数组,那么返回 ARRAY 。

如果其参数不是引用,那么返回一个 NULL 字符串,下面是 ref 函数的可能返回值:

REF     指向指针的指针

SCALAR     指向标量的指针

ARRAY     指向数组的指针

HASH      指向散列的指针

CODE    指向子例程的指针

GLOB    指向
typeglob
的指针

考虑下面代码:
[code=perl]#!/usr/bin/perl


sub gifts;      #前向声明
$sum = 5;
$junk = "xxx";
@toys = qw/car gun tank/;


$p = \$sum;
$pp = \$p;


local %hashtemp = (
                   "name"  => "Jasmine",
                   "score" => 100,
                  );


sub subtemp {
        print "hello perl\n";
}




gifts(\$num, \@toys, \%hashtemp, \&subtemp, \$pp, \*globp, $junk);


sub gifts  {
        my ($n, $t, $h, $s, $pp, $globp, $j) = @_;
        print "\$n is a reference.\n" if ref($n);
        print "\$t is a reference.\n" if ref($t);
        print "\h is a reference.\n" if ref($h);
        print "\$s is a reference.\n" if ref($s);
        print "\$pp is a reference.\n" if ref($pp);
        print "\$globp is a reference.\n" if ref($globp);
        print "\$junk is not a reference.\n" unless ref($junk);


        print "--------------------------------\n";


        printf "\$n is a reference to a %s.\n", ref($n);
        printf "\$t is a reference to an %s.\n", ref($t);
        printf "\$h is a reference to a %s.\n", ref($h);
        printf "\$s is a reference to a %s.\n", ref($s);
        printf "\$pp is a reference to a %s.\n", ref($pp);
        printf "\$globp is a reference to a %s.\n", ref($globp);


}[/mw_shl_code]
运行输出:
]$ ./ref.pl
$n is a reference.
$t is a reference.
h is a reference.
$s is a reference.
$pp is a reference.
$globp is a reference.
$junk is not a reference.
--------------------------------
$n is a reference to a SCALAR.
$t is a reference to an ARRAY.
$h is a reference to a HASH.
$s is a reference to a CODE.
$pp is a reference to a REF.
$globp is a reference to a GLOB.

如果 ref 的参数是一个指向某个对象的指针,那么函数就返回这个对象所归属到的包的名称,如:
[code=perl]#!/usr/bin/perl

package House;

my $ref = {
                "Owner"  => "Tom",
                "Price"  => "25000",
};

bless ($ref, House);

print "The bless function tags the hash with its package name.\n";

print "The value of \$ref is: $ref. \n";

print "The ref function returns the class (package) name:", ref($ref), ".\n";[/mw_shl_code]
运行输出:
$ ./object.pl
The bless function tags the hash with its package name.
The value of $ref is: House=HASH(0x8737830).
The ref function returns the class (package) name:House.
上面最后一句打印出了对象(就是某个包内的一个散列表)所归属的包的名(House)。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-19 02:41 , Processed in 0.061052 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表