|
ref 函数可以用来判断引用是否存在。如果它的参数是一个指针(引用)变量,那么 ref 就返回该引用指向的数据类型。比如指针指向的是标量,那么返回 SCALAR;又如指向的是数组,那么返回 ARRAY 。
如果其参数不是引用,那么返回一个 NULL 字符串,下面是 ref 函数的可能返回值:
REF 指向指针的指针
SCALAR 指向标量的指针
ARRAY 指向数组的指针
HASH 指向散列的指针
CODE 指向子例程的指针
GLOB 指向 的指针
考虑下面代码:
[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)。 |
|