引用
$ 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. 二、举例
简单来说,就是如果一个变量是个引用,那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