在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来了解其类型,如果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