陣列引用

陣列引用是引用陣列的標量($)。

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。