Who Needs Complicated Data Structures?
The Solution
An Example
Arrow Rule
The Rest


perlreftut − Mark’s very short tutorial about references


One of the most important new features in Perl 5 was the capability to manage complicated data structures like multidimensional arrays and nested hashes. To enable these, Perl 5 introduced a feature called ‘references’, and using references is the key to managing complicated, structured data in Perl. Unfortunately, there’s a lot of funny syntax to learn, and the main manual page can be hard to follow. The manual is quite complete, and sometimes people find that a problem, because it can be hard to tell what is important and what isn’t.

Fortunately, you only need to know 10% of what’s in the main page to get 90% of the benefit. This page will show you that 10%.

Who Needs Complicated Data Structures?


Why would you want a hash of lists? Let’s take a simple example: You have a file of city and country names, like this:

        Chicago, USA
        Frankfurt, Germany
        Berlin, Germany
        Washington, USA
        Helsinki, Finland
        New York, USA


        Finland: Helsinki.
        Germany: Berlin, Frankfurt.
        USA:  Chicago, New York, Washington.


If hash values can’t be lists, you lose. In Perl 4, hash values can’t be lists; they can only be strings. You lose. You’d probably have to combine all the cities into a single string somehow, and then when time came to write the output, you’d have to break the string into a list, sort the list, and turn it back into a string. This is messy and error-prone. And it’s frustrating, because Perl already has perfectly good lists that would solve the problem if only you could use them.

The Solution


A reference is a scalar value that refers to an entire array or an entire hash (or to just about anything else). Names are one kind of reference that you’re already familiar with. Think of the President: a messy, inconvenient bag of blood and bones. But to talk about him, or to represent him in a computer program, all you need is the easy, convenient scalar string "Bill Clinton".

References in Perl are like names for arrays and hashes. They’re Perl’s private, internal names, so you can be sure they’re unambiguous. Unlike "Bill Clinton", a reference only refers to one thing, and you always know what it refers to. If you have a reference to an array, you can recover the entire array from it. If you have a reference to a hash, you can recover the entire hash. But the reference is still an easy, compact scalar value.

You can’t have a hash whose values are arrays; hash values can only be scalars. We’re stuck with that. But a single reference can refer to an entire array, and references are scalars, so you can have a hash of references to arrays, and it’ll act a lot like a hash of arrays, and it’ll be just as useful as a hash of arrays.

We’ll come back to this city-country problem later, after we’ve seen some syntax for managing references.



Making References

Make Rule 1





These examples show how to make references to variables with names. Sometimes you want to make an array or a hash that doesn’t have a name. This is analogous to the way you like to be able to use the string "\n" or the number 80 without having to store it in a named variable first.

Make Rule 2


    # $aref now holds a reference to an array

    # $href now holds a reference to a hash


        # This:
        $aref = [ 1, 2, 3 ];

        # Does the same as this:
        @array = (1, 2, 3);
        $aref = \@array;

The first line is an abbreviation for the following two lines, except that it doesn’t create the superfluous array variable @array.

Using References

What can you do with a reference once you have it? It’s a scalar value, and we’ve seen that you can store it as a scalar and get it back again just like any scalar. There are just two more ways to use it:

Use Rule 1


Here are some examples of that:


        @a              @{$aref}                An array
        reverse @a      reverse @{$aref}        Reverse the array

On each line are two expressions that do the same thing. The left-hand versions operate on the array @a, and the right-hand versions operate on the array that is referred to by $aref, but once they find the array they’re operating on, they do the same things to the arrays.

Using a hash reference is exactly the same:

        %h              %{$href}              A hash
        $h{’red’}       ${$href}{’red’}       An element of the hash
        $h{’red’} = 17  ${$href}{’red’} = 17  Assigning an element

Use Rule 2



Most often, when you have an array or a hash, you want to get or set a single element from it. ${$aref}[3] and ${$href}{’red’} have too much punctuation, and Perl lets you abbreviate.

If $aref holds a reference to an array, then $aref->[3] is the fourth element of the array. Don’t confuse this with $aref[3], which is the fourth element of a totally different array, one deceptively named @aref. $aref and @aref are unrelated the same way that $item and @item are.

Similarly, $href->{’red’} is part of the hash referred to by the scalar variable $href, perhaps even one with no name. $href{’red’} is part of the deceptively named %href hash. It’s easy to forget to leave out the ->, and if you do, you’ll get bizarre results when your program gets array and hash elements out of totally unexpected hashes and arrays that weren’t the ones you wanted to use.

An Example

Let’s see a quick example of how all this is useful.


Now think about

        @a = ( [1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]



The notation still looks a little cumbersome, so there’s one more abbreviation:

Arrow Rule

In between two subscripts, the arrow is optional.


Now it really looks like two-dimensional arrays!




    1   while (<>) {
    2     chomp;
    5   }
    7   foreach $country (sort keys %table) {
    8     print "$country: ";
   10     print join ’, ’, sort @cities;
   11     print ".\n";
   12   }



        push @array, $city;



        @cities = @array;


The rest of the program is just familiar uses of chomp, split, sort, print, and doesn’t involve references at all.

There’s one fine point I skipped. Suppose the program has just read the first line in its input that happens to mention Greece. Control is at line 4, $country is ’Greece’, and $city is ’Athens’. Since this is the first city in Greece, $table{$country} is undefined---in fact there isn’t an ’Greece’ key in %table at all. What does line 4 do here?


This is Perl, so it does the exact right thing. It sees that you want to push Athens onto an array that doesn’t exist, so it helpfully makes a new, empty, anonymous array for you, installs it in the table, and then pushes Athens onto it. This is called ‘autovivification’.

The Rest


Some of the highlights of the perlref manpage:



To see if a variable contains a reference, use the ‘ref’ function. It returns true if its argument is a reference. Actually it’s a little better than that: It returns HASH for hash references and ARRAY for array references.


        ARRAY(0x80f5dec)   or    HASH(0x826afc0)

If you ever see a string that looks like this, you’ll know you printed out a reference by mistake.


You can use a string as if it were a reference. If you use the string "foo" as an array reference, it’s taken to be a reference to the array @foo. This is called a soft reference or symbolic reference.

You might prefer to go on to the perllol manpage instead of the perlref manpage; it discusses lists of lists and multidimensional arrays in detail. After that, you should move on to the perldsc manpage; it’s a Data Structure Cookbook that shows recipes for using and printing out arrays of hashes, hashes of arrays, and other kinds of data.




Author: Mark-Jason Dominus, Plover Systems (

This article originally appeared in The Perl Journal ( volume 3, #2. Reprinted with permission.

The original title was Understand References Today.

Distribution Conditions

Copyright 1998 The Perl Journal.

When included as part of the Standard Version of Perl, or as part of its complete documentation whether printed or otherwise, this work may be distributed only under the terms of Perl’s Artistic License. Any distribution of this file or derivatives thereof outside of that package require that special arrangements be made with copyright holder.
