使用reference的目的
1. 创建@_,会拷贝整个array或hash,浪费内存空间
2.@_在子程序中是传入数据的拷贝,无法对修改传入的数据
与C语言对比的话,Perl的reference更像指针,或者C++的引用
the backslash(/) character is also the "take a reference to" operator.
反斜线符号还是引用操作符
-------------------------------------------------------------------------------------------
1.Reference to Array
对数组的引用
my @array = qw(a b c d e f g);
my $array_ref = /@array;
dereference to array
解引用整体数组
@{$array_ref}
引用数组元素
$array[1]
${$array_ref}[1]
很多情况下,需要解引用的数组引用是一个标量值,如@{$array_ref}或${$array_ref}[1]
这种情况下,可以丢弃{},即@$array_ref或$$array_ref[1]
-------------------------------------------------------------------------------------------
Reference to Hash
对哈希的引用
my %hash = (
a => 1,
b => 2,
c => 3,
d => 4,
);
my $hash_ref = /%hash;
my $elem0 = $hash{'a'};
my $elem0 = ${$hash_ref}{'a'};
my $elem0 = $$hash_ref{'a'};
my @keys = keys %{$hash_ref};
my @keys = keys %$hash_ref;
引用哈希表中的值
my $val = $hash_ref->{'a'};
Variable | Instantiating the scalar |
Instantiating a reference to it |
Referencing it | Dereferencing it | Accessing an element |
$scalar | $scalar = "steve"; |
$ref = /"steve"; |
$ref = /$scalar | $$ref or ${$ref} |
N/A |
@list | @list = ("steve","fred"); |
$ref = ["steve","fred"]; |
$ref = /@list | @{$ref} | ${$ref}[3] $ref->[3] |
%hash | %hash = ("name" => "steve", "job" => "Troubleshooter"); |
$hash = {"name" => "steve", "job" => "Troubleshooter"}; |
$ref = /%hash | %{$ref} | ${$ref}{"president"} $ref->{"president"} |
FILE | $ref = /*FILE | {$ref} or scalar <$ref> |
引用自http://www.troubleshooters.com/codecorn/littperl/perlsub.htm