Perl Basics   «Prev  Next»

Lesson 19 Array references
ObjectiveLearn how to use references to arrays.

Perl Array References

In the previous lesson you learned about Perl's capacity to create and use references to data. Specifically, you learned about scalar references.In this lesson we will cover references to arrays. References to arrays are just like references to scalars, where the only difference is that the reference knows it points to an array.

You can create a reference to an array like this:
@presidents = qw( Franklin Harry Dwight 
John Lyndon Richard Gerald Jimmy Ronald George Bill );   
$arrayref   = \@presidents;

This will create a reference that points to the array.
Reference to an array diagram
Reference to an array diagram


What are references to arrays in Perl?

In Perl, a reference to an array is a scalar value that points to an array rather than storing the array directly. It allows you to create more complex data structures and manipulate arrays dynamically. A reference to an array can be created using the backslash operator \@ before the name of the array:
my @array = (1, 2, 3);
my $array_ref = \@array;

Once you have a reference to an array, you can access its elements by using the arrow operator -> and square brackets []:
print $array_ref->[0]; # prints 1
print $array_ref->[1]; # prints 2

Referencing arrays in this way allows you to pass arrays to subroutines, return arrays from subroutines, store arrays in hashes, and build complex data structures like arrays of arrays.

You can get at the values in the array like this:
$$arrayref[1]   # an element of the dereferenced array
$arrayref       # the whole dereferenced array

Optionally, you can dereference an array with the special arrow operator:
$arrayref->[1]        # an element of the array


You can also create anonymous arrays that are accessible only via reference.
This may seem pointless now, but we will use it quite a bit later. So take a minute now to work through an example of an Anonymous Array.

Array References Quiz

Anonymous hashes are very similar to anonymous arrays.
Clink the link Array References - Quiz to take the array references quiz.

Perl Complete Reference