数组引用

数组引用是引用数组的标量($)。

my @array = ("Hello"); # Creating array, assigning value from a list
my $array_reference = \@array;

这些可以更简洁地创建如下:

my $other_array_reference = ["Hello"];

修改/使用数组引用需要首先解除引用它们。

my @contents = @{ $array_reference };               # Prefix notation
my @contents = @$array_reference;                   # Braces can be left out

Version >= 5.24.0

新的后缀解除引用语法,默认情况下从 v5.24 开始提供

use v5.24;
my @contents = $array_reference->@*; # New postfix notation 

当通过索引访问 arrayref 的内容时,你可以使用 -> 语法糖。

my @array = qw(one two three);      my $arrayref = [ qw(one two three) ]
my $one = $array[0];                my $one = $arrayref->[0];

与数组不同,arrayrefs 可以嵌套:

my @array = ( (1, 0), (0, 1) )  # ONE array of FOUR elements: (1, 0, 0, 1)
my @matrix = ( [1, 0], [0, 1] ) # an array of two arrayrefs
my $matrix = [ [0, 1], [1, 0] ] # an arrayref of arrayrefs
# There is no namespace conflict between scalars, arrays and hashes
# so @matrix and $matrix _both_ exist at this point and hold different values.

my @diagonal_1 = ($matrix[0]->[1], $matrix[1]->[0])     # uses @matrix
my @diagonal_2 = ($matrix->[0]->[1], $matrix->[1]->[0]) # uses $matrix
# Since chained []- and {}-access can only happen on references, you can
# omit some of those arrows.
my $corner_1 = $matrix[0][1];   # uses @matrix;
my $corner_2 = $matrix->[0][1]; # uses $matrix;  

当用作布尔值时,引用始终为 true。