TExcelTAD
Home › Perl › Perl References

Perl References

A reference is a scalar that points to another piece of data: an array, a hash, a scalar or a subroutine. References are how Perl builds nested data structures, passes several arrays to a sub, and implements objects.

Taking a reference

Put a backslash \ in front of a variable to get a reference to it. Printing a reference shows its type and memory address, which is not very useful, so we use ref to inspect it:

perl · try it yourself
use strict;
use warnings;

my @colors = qw(red green blue);
my %ages   = (ana => 31, raj => 28);
my $pi     = 3.14;

my $colors_ref = \@colors;
my $ages_ref   = \%ages;
my $pi_ref     = \$pi;

print "colors_ref is a ", ref($colors_ref), "\n";
print "ages_ref is a ",   ref($ages_ref),   "\n";
print "pi_ref is a ",     ref($pi_ref),     "\n";
print "plain scalar: '", ref($pi), "'\n";
colors_ref is a ARRAY
ages_ref is a HASH
pi_ref is a SCALAR
plain scalar: ''

ref returns ARRAY, HASH, SCALAR, CODE (and a class name for objects), or the empty string for a non-reference.

Dereferencing

To get the data back, dereference. There are three equivalent notations; the arrow -> is the one you will use most for single elements:

Want Block syntax Arrow syntax Postfix (5.24+)
whole array @{$aref} or @$aref $aref->@*
one element ${$aref}[0] $aref->[0]
last index $#{$aref} or $#$aref $aref->$#*
whole hash %{$href} or %$href $href->%*
one value ${$href}{key} $href->{key}
scalar ${$sref} or $sref $sref->$*
perl · try it yourself
use strict;
use warnings;

my @colors = qw(red green blue);
my $cref = \@colors;

print "All: @$cref\n";
print "First: $cref->[0]\n";
print "Count: ", scalar(@$cref), "\n";
print "Postfix: ", join("/", $cref->@*), "\n";

my %ages = (ana => 31, raj => 28);
my $aref = \%ages;
print "Ana is $aref->{ana}\n";
print "Names: ", join(", ", sort keys %$aref), "\n";
All: red green blue
First: red
Count: 3
Postfix: red/green/blue
Ana is 31
Names: ana, raj

References share data

A reference points to the same data, it does not copy it. Changing data through the reference changes the original:

perl · try it yourself
use strict;
use warnings;

my @scores = (70, 80);
my $ref = \@scores;

push @$ref, 90;
$ref->[0] = 75;
print "Original array: @scores\n";

my @copy = @$ref;        # copying the elements makes an independent array
$copy[0] = 0;
print "After changing the copy: @scores\n";
Original array: 75 80 90
After changing the copy: 75 80 90

Anonymous arrays and hashes

You often don't need a named variable at all. Square brackets create a reference to a new anonymous array, and curly braces a reference to a new anonymous hash:

perl · try it yourself
use strict;
use warnings;

my $primes = [2, 3, 5, 7];
my $book   = { title => "Dune", year => 1965 };

print "Third prime: $primes->[2]\n";
print "$book->{title} ($book->{year})\n";

$book->{pages} = 412;
print "Keys: ", join(", ", sort keys %$book), "\n";
Third prime: 5
Dune (1965)
Keys: pages, title, year

Remember: ( ... ) is a list, [ ... ] is a reference to an array, { ... } is a reference to a hash.

Passing arrays to subs

Because a reference is a single scalar, passing references avoids the flattening of @_:

perl · try it yourself
use strict;
use warnings;
use feature 'signatures';

sub compare_lists ($first, $second) {
    my $n1 = @$first;
    my $n2 = @$second;
    return "first has $n1 items, second has $n2";
}

sub add_bonus ($scores, $bonus) {
    $_ += $bonus for @$scores;    # modifies the caller's array
}

my @team_a = (10, 20, 30);
my @team_b = (5, 15);
print compare_lists(\@team_a, \@team_b), "\n";

add_bonus(\@team_b, 100);
print "Team B now: @team_b\n";
first has 3 items, second has 2
Team B now: 105 115

Checking a reference before using it

Dereferencing something of the wrong type is a fatal error under strict. Check with ref when your code accepts different kinds of input:

perl · try it yourself
use strict;
use warnings;

sub describe {
    my ($thing) = @_;
    my $type = ref $thing;
    return "array of " . scalar(@$thing) if $type eq 'ARRAY';
    return "hash with keys " . join(",", sort keys %$thing) if $type eq 'HASH';
    return "plain value $thing" if $type eq '';
    return "something else: $type";
}

print describe([1, 2, 3]), "\n";
print describe({ x => 1, y => 2 }), "\n";
print describe(42), "\n";
print describe(\"text"), "\n";
array of 3
hash with keys x,y
plain value 42
something else: SCALAR

Test yourself

What does [1, 2, 3] create?

  1. A list
  2. A reference to an anonymous array
  3. A hash
  4. A slice

Given my $h = { a => 1 };, how do you read the value of a?

  1. $h{a}
  2. %h->{a}
  3. $h->{a}
  4. @h{a}

What does ref(\@list) return?

  1. LIST
  2. ARRAY
  3. REF
  4. the number of elements