建立引用
建立规则1:在数组或者哈希前加反斜杠
$aref = \@array; # $aref now holds a reference to @array
$href = \%hash; # $href now holds a reference to %hash
当引用被储存在变量里,就能够如普通变量般使用。
建立规则2: [items]建立一个新的匿名数组,且返回一个指向数组的引用。{items}建立一个新的匿名哈希,且返回一个指向哈希的引用。
$aref = [ 1, "foo", undef, 13 ];
# $aref now holds a reference to an array
$href = { APR => 4, AUG => 8 };
# $href now holds a reference to a hash
规则1,规则2的比较:
# This:
$aref = [ 1, 2, 3 ];
# Does the same as this:
@array = (1, 2, 3);
$aref = \@array;
使用引用数组
使用规则 1
使用引用的时候,你能够将变量放到大括号里,来代替数组. eg:@{$aref} instead of @array
@a @{$aref} An array
reverse @a reverse @{$aref} Reverse the array
$a[3] ${$aref}[3] An element of the array
$a[3] = 17; ${$aref}[3] = 17 Assigning an element
%h %{$href} A hash
keys %h keys %{$href} Get the keys from the hash
$h{'red'} ${$href}{'red'} An element of the hash
$h{'red'} = 17 ${$href}{'red'} = 17 Assigning an elementide
使用规则 2
规则1的写法比较难于阅读,因此,们能够用简写的形式,来方便的阅读引用。
${$aref}[3] $aref->[3]
${$href}{red} $href->{red}
以上两种写法表达的是相同的内容this
箭头规则
@a = ( [1, 2, 3],
[4, 5, 6],
[7, 8, 9]
);
$a[1] 包含一个匿名数组,列表为(4,5,6),它同时也是一个引用,使用规则2,咱们能够这样写:$a[1]->[2] 值为6 ;相似的,$a[1]->[2]的值为2,这样,看起来像是一个二维数组。 使用箭头规则,还能够写的更加简单:
Instead of $a[1]->[2], we can write $a[1][2]
Instead of $a[0]->[1] = 23, we can write $a[0][1] = 23 这样,看起来就像是真正的二维数据了。
element