Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 43 ยท References and Data

References

Learn Perl references: the backslash operator, arrow dereferencing, array, hash and code refs, ref(), anonymous structures, autovivification and weak references.

A reference is a scalar that points to another piece of data. Instead of holding a number or a string, it holds the location of an array, a hash, a subroutine or another scalar. References are what make nested data possible in Perl: an array can only hold scalars, but a scalar can be a reference to a whole array, so you can build lists of lists and hashes of hashes.

References also let you pass big structures to subroutines without copying them, return several arrays from one function, and hand a piece of code to another piece of code. Almost every real Perl program uses them, so this chapter is the turning point between beginner Perl and everyday Perl.

Perl is not installed on this site, so the Perl code below is read-only. The interactive examples are Python stand-ins that show the same ideas (names that point at shared data), and each one says what the Perl equivalent is.

Making a reference with the backslash

The backslash operator \ takes a reference to whatever follows it. The result is an ordinary scalar, so you store it in a $ variable.

PERL
use v5.36;

my @colors = ('red', 'green', 'blue');
my %ages   = (ana => 31, ben => 27);
my $count  = 3;

my $colors_ref = \@colors;
my $ages_ref   = \%ages;
my $count_ref  = \$count;

say ref($colors_ref);   # ARRAY
say ref($ages_ref);     # HASH
say ref($count_ref);    # SCALAR

The function ref tells you what kind of thing a reference points to. It returns an empty string for values that are not references, which makes it handy as a check.

A reference is a scalar

Points It holds where the data lives, not the data.
Fits in $ One scalar can name a whole array or hash.
Shared Copying the reference does not copy the data.
1 / 2

Dereferencing with the arrow and with sigils

To get at the data again you dereference. For element access, the arrow -> is the clearest form.

PERL
use v5.36;

my $colors_ref = ['red', 'green', 'blue'];
my $ages_ref   = { ana => 31, ben => 27 };

say $colors_ref->[0];        # red
say $ages_ref->{ana};        # 31
say scalar @$colors_ref;     # 3
say join ', ', @{$colors_ref};   # red, green, blue
say join ', ', sort keys %$ages_ref;   # ana, ben

Two spellings appear in real code:

  • $ref->[0] and $ref->{key} access a single element.
  • @$ref, @{$ref}, %$ref and %{$ref} use the whole array or hash. The braces are optional for a simple variable and required when the reference comes from an expression, as in @{ $self->{items} }.

Between two subscripts the arrow is optional. $data->{list}[2]{name} means the same as $data->{list}->[2]->{name}, and the short form is what you will see everywhere.

Since Perl 5.24 there is also postfix dereferencing, which reads left to right: $ref->@* is the whole array, $ref->%* is the whole hash, $ref->$#* is the last index, and $ref->@[0,1] is a slice. It is enabled by default in modern Perl (use v5.24 or later).

PERL
my @all  = $colors_ref->@*;
my $last = $colors_ref->$#*;

Anonymous structures

You do not need a named variable to have a reference. Square brackets create an anonymous array and curly braces create an anonymous hash, each returning a reference at once.

PERL
my $point = { x => 3, y => 4 };
my $row   = [1, 2, 3];
my $table = [ [1, 2], [3, 4] ];     # array of arrays

Look at what the stand-in below does. Python names are references too, so two names can point at one list. Change it through one name and the other sees the change, exactly as with two copies of the same Perl array reference.

Python Stand-in: two names, one list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Perl, my $b = $a copies the reference, so both scalars point at the same array. my @c = @$a builds a brand new array with copies of the elements. This difference is the most common source of "why did my data change?" bugs.

Passing references to subroutines

A subroutine receives its arguments flattened into one list, so two arrays passed side by side merge into one. Passing references keeps them apart and avoids copying large lists.

PERL
use v5.36;

sub average_gap ($first, $second) {
    my $sum1 = 0; $sum1 += $_ for @$first;
    my $sum2 = 0; $sum2 += $_ for @$second;
    return $sum2 / @$second - $sum1 / @$first;
}

my @a = (1, 2, 3);
my @b = (10, 20, 30);
say average_gap(\@a, \@b);   # 18

If the subroutine changes @$first, the caller's @a changes as well, because they are the same array. Do this only when it is the intended behavior and document it.

Code references

A reference to a subroutine is a code reference. Take one with \&name or build one with sub { ... } (an anonymous subroutine), and call it with ->(...).

PERL
use v5.36;

sub double ($n) { return $n * 2 }

my $by_name = \&double;
my $by_hand = sub ($n) { return $n + 100 };

say $by_name->(21);    # 42
say $by_hand->(1);     # 101

my %actions = (
    double => $by_name,
    bump   => $by_hand,
);
say $actions{bump}->(5);   # 105

Storing code references in a hash gives you a dispatch table, a clean replacement for long if/elsif chains. You will see more of this in Scope, Closures and Recursion.

Python Stand-in: a dispatch table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Checking what you have with ref

ref is how a subroutine can accept several shapes of input. Some values to remember:

  • ref([]) is ARRAY, ref({}) is HASH, ref(sub {}) is CODE, ref(\1) is SCALAR.
  • ref(\$ref) is REF when $ref itself holds a reference: a reference to a reference.
  • ref("text") is the empty string, which is false.
  • For an object, ref returns the class name (see Classes and Objects).
PERL
sub describe ($thing) {
    my $kind = ref $thing;
    return 'plain value' if !$kind;
    return "list of " . @$thing . " items" if $kind eq 'ARRAY';
    return "map with " . keys(%$thing) . " keys" if $kind eq 'HASH';
    return "something else ($kind)";
}

Autovivification

When you use an undefined scalar as if it were a reference, Perl quietly creates the structure for you. This is called autovivification, and it is why building nested data is so short.

PERL
use v5.36;

my %seen;
push $seen{fruit}->@*, 'apple';     # $seen{fruit} becomes []
$seen{count}{apple}++;              # $seen{count} becomes {}

say scalar @{ $seen{fruit} };       # 1
say $seen{count}{apple};            # 1

It also has a surprise. Merely reading a deep path creates the middle levels.

PERL
my %config;
my $x = $config{db}{host};          # reads nothing, but...
say exists $config{db} ? 'db exists' : 'no db';   # db exists

To test for a deep key without creating anything, check each level: if (exists $config{db} && exists $config{db}{host}). The no autovivification module on CPAN can turn the behavior off, but plain checks are usually enough.

Reference counting and weak references

Perl frees data when nothing points at it any more. Each piece of data carries a count of references, and when the count reaches zero the memory is released. This works well, except for circular references: if A points at B and B points back at A, neither count reaches zero, so the pair is never freed until the program ends.

The core module Scalar::Util provides weaken to break the cycle. A weak reference does not add to the count, and it becomes undef automatically if its target disappears.

PERL
use v5.36;
use Scalar::Util qw(weaken);

my $parent = { name => 'root', children => [] };
my $child  = { name => 'leaf', parent => $parent };
weaken($child->{parent});          # child -> parent no longer keeps it alive
push $parent->{children}->@*, $child;

You will need weaken mainly for trees, doubly linked lists and objects that refer to their owners.

Common mistakes

  • Forgetting to dereference. print @colors_ref prints a string like ARRAY(0x55d0c8), not the elements. Use @$colors_ref.
  • Comparing references with ==. It compares addresses, which is rarely what you want.
  • Using @{$x}[0] when you mean ${$x}[0] or $x->[0]. Prefer the arrow.
  • Confusing { } as a block and as a hash. Perl guesses. Write +{ ... } to force a hash and {; ... } to force a block.
  • Copying structures by assigning the reference. To copy nested data you need a deep copy, which is the topic of Nested Data Structures.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does my $b = $a; do when $a holds an array reference?

    Assigning a reference copies only the pointer. Both variables now refer to one array, so a change through either name is visible through the other.
  2. 2. Which expression creates a reference to an anonymous hash?

    Curly braces in an expression create an anonymous hash and return a reference to it. Square brackets make an array reference, and sub makes a code reference.
  3. 3. What does ref(sub { 1 }) return?

    A reference to a subroutine is a code reference, and ref reports it as CODE.
  4. 4. What is autovivification?

    Using an undef scalar as an array or hash reference makes Perl create the structure on the spot. Reading $h{a}{b} also creates $h{a}.
  5. 5. Why would you call Scalar::Util::weaken on a reference?

    A weak reference does not raise the reference count, so a parent-child cycle can still be freed when the rest of the program stops using it.

Summary

  • A reference is a scalar that points to data. \ makes one; [ ], { } and sub { } make anonymous ones.
  • Dereference with ->[ ], ->{ }, ->( ), or with @$ref, %$ref and postfix ->@*.
  • ref returns ARRAY, HASH, CODE, SCALAR, REF, a class name, or an empty string.
  • Copying a reference shares the data; copying @$ref copies the elements.
  • Autovivification creates nested structures on demand, including when you only read.
  • weaken breaks reference cycles so memory is released.

Next, build and work with bigger structures in Nested Data Structures.