Perl Basics   «Prev  Next»

Lesson 19 Array References
Objective Learn how to create, dereference, and use array references and anonymous arrays in Perl.

Perl Array References

In previous lessons, you learned that Perl can create references—scalar values that point to other data. Here, we focus on references to arrays. An array reference behaves much like a scalar reference, except that it points to an array. You can create a reference to an array using the backslash operator:



@presidents = qw(Franklin Harry Dwight John Lyndon Richard Gerald Jimmy Ronald George Bill);
$arrayref   = \@presidents;

This code creates $arrayref as a reference pointing to @presidents. You can then access or manipulate the array through the reference.

Reference to an array diagram
Reference to an array diagram


What Are References to Arrays in Perl?

A reference to an array is a scalar variable that holds the memory address of an array instead of its contents. This approach enables more flexible and memory-efficient data manipulation. You can create a reference and access its elements as follows:


my @array = (1, 2, 3);
my $array_ref = \@array;

print $array_ref->[0]; # prints 1
print $array_ref->[1]; # prints 2

The arrow operator (->) is used to dereference and access individual array elements. You can also dereference using double dollar signs:


$$arrayref[1];   # Access an element
@$arrayref;      # Dereference the entire array

Anonymous Arrays

An anonymous array is an array that exists without a name and is accessible only through a reference. You create one using square brackets:


$arrayref = ['one', 'two', 'three'];

Here, $arrayref holds a reference to an unnamed array. You can also create multidimensional (nested) arrays:


$arrayref = ['one', 'two', [1, 2, 3], 'four'];

You can access nested array elements using chained indices:


$arrayref->[1];      # 'two'
$arrayref->[2][1];   # 2

Perl allows arrays to expand dynamically, even when nested:



$arrayref->[2][3] = 4;   # Expands the nested array

Now $arrayref points to:


['one', 'two', [1, 2, 3, 4], 'four']

References to Anonymous Storage

So far, you’ve seen references to existing variables. Perl can also create references to anonymous storage—data that has no variable name. Using square brackets automatically allocates anonymous storage and returns a reference to it:


$ra = [ ];          # Empty anonymous array
$ra = [1, "hello"]; # Initialized anonymous array
  1. The first line creates an empty array and returns a reference to it.
  2. The second creates an initialized anonymous array and returns a reference.

This behavior is similar to malloc() in C—it allocates memory dynamically. If you mistakenly use parentheses instead of brackets, Perl evaluates the expression and returns the last element instead of a reference:


$ra = (1, "hello");  # $ra now holds "hello", not a reference

Use Cases for Anonymous Arrays

Anonymous arrays are useful for building compact, flexible data structures. Common scenarios include:

  1. Temporary Arrays: Create short-lived arrays for one-time operations:
    
    print join(", ", @{[1, 2, 3, 4, 5]}), "\n";
        

  2. Passing Arrays to Functions: Pass an array to a subroutine without naming it:
    
    sub print_array {
        my ($array_ref) = @_;
        print join(", ", @$array_ref), "\n";
    }
    
    print_array([1, 2, 3, 4, 5]);
        
  3. Nested Arrays: Create multidimensional data structures:
    
    my $matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ];
        
  4. Arrays Within Hashes: Store arrays as hash values:
    
    my %grades = (
        "John" => [90, 85, 78],
        "Jane" => [95, 88, 92],
        "Mary" => [88, 90, 76]
    );
        
  5. Returning Arrays from Functions: Return an array reference directly:
    
    sub create_array {
        my ($start, $end) = @_;
        return [($start .. $end)];
    }
    
    my $array_ref = create_array(1, 5);
    print join(", ", @$array_ref), "\n";
        

These examples demonstrate how anonymous arrays simplify passing, storing, and returning array data without creating unnecessary variable names.

Summary

Array references and anonymous arrays are powerful tools in Perl for managing complex data structures. They allow arrays to be nested, passed to subroutines, and stored in other data containers with minimal overhead. Mastering them prepares you for more advanced Perl techniques such as references to hashes, objects, and closures.

Array References Quiz

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


SEMrush Software