Perl 中的解引用


Perl 中的解引用返回引用点到位置的值。要解引用引用,只需使用 $、@ 或 % 作为引用变量的前缀,具体取决于引用指向的是标量、数组还是哈希。以下示例说明了该概念 -

示例

 在线演示

#!/usr/bin/perl
$var = 10;

# Now $r has reference to $var scalar.
$r = \$var;

# Print value available at the location stored in $r.
print "Value of $var is : ", $$r, "\n";
@var = (1, 2, 3);

# Now $r has reference to @var array.
$r = \@var;

# Print values available at the location stored in $r.
print "Value of @var is : ", @$r, "\n";
%var = ('key1' => 10, 'key2' => 20);

# Now $r has reference to %var hash.
$r = \%var;

# Print values available at the location stored in $r.
print "Value of %var is : ", %$r, "\n";

输出

当执行以上程序时,它产生以下结果 -

Value of 10 is : 10
Value of 1 2 3 is : 123
Value of %var is : key220key110

如果你不确定变量类型,那么很容易使用 ref 来了解其类型,如果其参数是引用,它将返回以下字符串之一。否则,它返回 false -

SCALAR
ARRAY
HASH
CODE
GLOB
REF

示例

让我们尝试以下示例 -

 在线演示

#!/usr/bin/perl
$var = 10;
$r = \$var;
print "Reference type in r : ", ref($r), "\n";
@var = (1, 2, 3);
$r = \@var;
print "Reference type in r : ", ref($r), "\n";
%var = ('key1' => 10, 'key2' => 20);
$r = \%var;
print "Reference type in r : ", ref($r), "\n";

输出

当执行以上程序时,它产生以下结果 -

Reference type in r : SCALAR
Reference type in r : ARRAY
Reference type in r : HASH

更新于:29-11-2019

1K+ 查看

开启你的职业生涯

完成课程,获得认证

开始
广告