← Back to Perl Course | Chapter 6: References | Lesson 2 of 7

Array references

An array reference lets you carry a whole array around in a single scalar.

In this page:

  1. Array references

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

perl
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
Common Mistakes
  1. Writing @ref[0] instead of $ref->[0]
  2. Forgetting to dereference with @$ref when looping
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.