Taking References to Arrays

Problem

You need to manipulate an array by reference.

Solution

To get a reference to an array:

$aref               = \@array;
$anon_array         = [1, 3, 5, 7, 9];
$anon_copy          = [ @array ];
@$implicit_creation = (2, 4, 6, 8, 10);

To deference an array reference, precede it with an at sign (@):

push(@$anon_array, 11);

Or use a pointer arrow plus a bracketed subscript for a particular element:

$two = $implicit_creation->[0];

To get the last index number by reference, or the number of items in that referenced array:

$last_idx  = $#$aref;
$num_items = @$aref;

Or defensively embracing and forcing context:

$last_idx  = $#{ $aref };
$num_items = scalar @{ $aref };

Discussion

Here are array references in action:

# check whether $someref contains a simple array reference
if (ref($someref) ne 'ARRAY') {
    die "Expected an array reference, not $someref\n";
}

print "@{$array_ref}\n";        # print original data

@order = sort @{ $array_ref };  # sort it

push @{ $array_ref }, $item;    # append new element to orig array

If you can’t decide whether to use a reference to a named array or to create a new one, here’s a simplistic guideline that will prove right more often than not. Only take a reference to an existing array either to return the reference out of scope, thereby creating an anonymous array, or to pass the array by reference to a function. For virtually all other cases, use [@array] to create a new array reference with a copy of the old values.

Automatic reference counting and the backslash operator make ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.