Array references
An array reference lets you carry a whole array around in a single scalar.
In this page:
Array references
You create one with \@array or with the anonymous array constructor [1, 2, 3]. Access elements with the arrow $ref->[0], or with the block form ${$ref}[0], and get the whole array with @$ref or @{$ref}. Since the reference is a single scalar, it can be stored in other arrays and hashes.
Note:
The last index of an array reference is $#{$ref} or $#$ref, and its length is scalar(@$ref).
Example: Array references
use strict;
use warnings;
my @nums = (3, 1, 2);
my $aref = \@nums;
push @$aref, 4;
print "original array now: @nums\n";
print "second element: $aref->[1]\n";
print "length: ", scalar(@$aref), "\n";
print "last index: $#{$aref}\n";
my $anon = [10, 20, 30];
print "anonymous: @$anon\n";
print "slice: @{$anon}[0,1]\n";
for my $n (sort { $a <=> $b } @$aref) {
print "n=$n\n";
}
# Output:
# original array now: 3 1 2 4
# second element: 1
# length: 4
# last index: 3
# anonymous: 10 20 30
# slice: 10 20
# n=1
# n=2
# n=3
# n=4
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Writing @ref[0] instead of $ref->[0]
- Forgetting to dereference with @$ref when looping
- Thinking [1,2,3] and (1,2,3) are the same thing
Chapter Summary
- [ ... ] creates an anonymous array reference
- $ref->[i] reads an element
- @$ref is the whole array
- scalar(@$ref) is the length
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: