++ed by:

148 PAUSE users
123 non-PAUSE users.

Jesse Vincent
and 1 contributors


perlref - Perl references and nested data structures






Symbolic references are names of variables or other objects, just as a symbolic link in a Unix filesystem contains merely the name of a file. The *glob notation is something of a symbolic reference. (Symbolic references are sometimes called "soft references", but please don't call them that; references are confusing enough without useless synonyms.)



Making References

References can be created in several ways.


By using the backslash operator on a variable, subroutine, or value. (This works much like the & (address-of) operator in C.) This typically creates another reference to a variable, because there's already a reference to the variable in the symbol table. But the symbol table reference might go away, and you'll still have the reference that the backslash returned. Here are some examples:

    $scalarref = \$foo;
    $arrayref  = \@ARGV;
    $hashref   = \%ENV;
    $coderef   = \&handler;
    $globref   = \*foo;











    $hashref = {
        'Adam'  => 'Eve',
        'Clyde' => 'Bonnie',




    sub hashem {        { @_ } }   # silently wrong
    sub hashem {       +{ @_ } }   # ok
    sub hashem { return { @_ } }   # ok


    sub showem {       {; @_ } }   # ok
    sub showem { { return @_ } }   # ok





Note the semicolon. Except for the code inside not being immediately executed, a sub {} is not so much a declaration as it is an operator, like do{} or eval{}. (However, no matter how many times you execute that particular line (unless you're in an eval("...")), $coderef will still have a reference to the same anonymous subroutine.)

Anonymous subroutines act as closures with respect to my() variables, that is, variables lexically visible within the current scope. Closure is a notion out of the Lisp world that says if you define an anonymous function in a particular lexical context, it pretends to run in that context even when it's called outside the context.


You might also think of closure as a way to write a subroutine template without using eval(). Here's a small example of how closures work:

    sub newprint {
        my $x = shift;
    $h = newprint("Howdy");
    $g = newprint("Greetings");

    # Time passes...


This prints

    Howdy, world!
    Greetings, earthlings!

Note particularly that $x continues to refer to the value passed into newprint() despite "my $x" having gone out of scope by the time the anonymous subroutine runs. That's what a closure is all about.



References are often returned by special subroutines called constructors. Perl objects are just references to a special type of object that happens to know which package it's associated with. Constructors are just special subroutines that know how to create that association. They do so by starting with an ordinary reference, and it remains an ordinary reference even while it's also being an object. Constructors are often named new(). You can call them indirectly:


But that can produce ambiguous syntax in certain cases, so it's often better to use the direct method invocation approach:


    use Term::Cap;

    use Tk;
    $main    = MainWindow->new();
                            -borderwidth         => 2)




    $scalarref = *foo{SCALAR};
    $arrayref  = *ARGV{ARRAY};
    $hashref   = *ENV{HASH};
    $coderef   = *handler{CODE};
    $ioref     = *STDIN{IO};
    $globref   = *foo{GLOB};
    $formatref = *foo{FORMAT};

All of these are self-explanatory except for *foo{IO}. It returns the IO handle, used for file handles ("open" in perlfunc), sockets ("socket" in perlfunc and "socketpair" in perlfunc), and directory handles ("opendir" in perlfunc). For compatibility with previous versions of Perl, *foo{FILEHANDLE} is a synonym for *foo{IO}, though it is deprecated as of 5.8.0. If deprecation warnings are in effect, it will warn of its use.


*foo{IO} is an alternative to the *HANDLE mechanism given in "Typeglobs and Filehandles" in perldata for passing filehandles into or out of subroutines, or storing into larger data structures. Its disadvantage is that it won't create a new filehandle for you. Its advantage is that you have less risk of clobbering more than you want to with a typeglob assignment. (It still conflates file and directory handles, though.) However, if you assign the incoming value to a scalar instead of a typeglob as we do in the examples below, there's no risk of that happening.

    splutter(*STDOUT);          # pass the whole glob
    splutter(*STDOUT{IO});      # pass both file and dir handles

    sub splutter {
        my $fh = shift;

    $rec = get_rec(*STDIN);     # pass the whole glob
    $rec = get_rec(*STDIN{IO}); # pass both file and dir handles

    sub get_rec {
        my $fh = shift;
        return scalar <$fh>;

Using References



        $bar = $$scalarref;
        push(@$arrayref, $filename);
        $$arrayref[0] = "January";
        print $globref "output\n";

    It's important to understand that we are specifically not dereferencing $arrayref[0] or $hashref{"KEY"} there. The dereference of the scalar variable happens before it does any key lookups. Anything more complicated than a simple scalar variable must use methods 2 or 3 below. However, a "simple scalar" includes an identifier that itself uses method 1 recursively. Therefore, the following prints "howdy".

        $refrefref = \\\"howdy";
        print $$$$refrefref;

        $bar = ${$scalarref};
        push(@{$arrayref}, $filename);







        $coderef->(1,2,3);            # Subroutine call

    The left side of the arrow can be any expression returning a reference, including a previous dereference. Note that $array[$x] is not the same thing as $array->[$x] here:



    One more thing here. The arrow is optional between brackets subscripts, so you can shrink the above down to






Using a string or number as a reference produces a symbolic reference, as explained above. Using a reference as a number produces an integer representing its storage location in memory. The only useful thing to be done with this is to compare two references numerically to see whether they refer to the same location.

    if ($ref1 == $ref2) {  # cheap numeric compare of references
        print "refs 1 and 2 refer to the same thing\n";

Using a reference as a string produces both its referent's type, including any package blessing as described in perlobj, as well as the numeric address expressed in hex. The ref() operator returns just the type of thing the reference is pointing to, without the address. See "ref" in perlfunc for details and examples of its use.


A typeglob may be dereferenced the same way a reference can, because the dereference syntax always indicates the type of reference desired. So ${*foo} and ${\$foo} both indicate the same scalar variable.

Here's a trick for interpolating a subroutine call into a string:




Similarly, an expression that returns a reference to a scalar can be dereferenced via ${...}. Thus, the above expression may be written as:


Symbolic references

We said that references spring into existence as necessary if they are undefined, but we didn't say what happens if a value used as a reference is already defined, but isn't a hard reference. If you use it as a reference, it'll be treated as a symbolic reference. That is, the value of the scalar is taken to be the name of a variable, rather than a direct link to a (possibly) anonymous value.


    $name = "foo";
    $$name = 1;                 # Sets $foo
    ${$name} = 2;               # Sets $foo
    @$name = ();                # Clears @foo
    $pack = "THAT";


    use strict 'refs';


    no strict 'refs';


    local $value = 10;
    $ref = "value";
        my $value = 20;
        print $$ref;


Not-so-symbolic references


    $push = "pop on ";
    print "${push}over";

has always meant to print "pop on over", even though push is a reserved word. This has been generalized to work the same outside of quotes, so that

    print ${push} . "over";

and even

    print ${ push } . "over";

will have the same effect. (This would have been a syntax error in Perl 5.000, though Perl 4 allowed it in the spaceless form.) This construct is not considered to be a symbolic reference when you're using strict refs:

    use strict 'refs';
    ${ bareword };      # Okay, means $bareword.



you can write just

    $array{ aaa }{ bbb }{ ccc }


    $array{ shift }


    $array{ shift() }
    $array{ +shift }
    $array{ shift @_ }

The use warnings pragma or the -w switch will warn you if it interprets a reserved word as a string. But it will no longer warn you about using lowercase words, because the string is effectively quoted.

Pseudo-hashes: Using an array as a hash

Pseudo-hashes have been removed from Perl. The 'fields' pragma remains available.

Function Templates

As explained above, an anonymous function with access to the lexical variables visible when that function was compiled, creates a closure. It retains access to those variables even though it doesn't get run until later, such as in a signal handler or a Tk callback.



The red() and green() functions would be similar. To create these, we'll assign a closure to a typeglob of the name of the function we're trying to build.

    for my $name (@colors) {
        no strict 'refs';       # allow symbol table manipulation





Access to lexicals that change over time--like those in the for loop above, basically aliases to elements from the surrounding lexical scopes-- only works with anonymous subs, not with named subroutines. Generally said, named subroutines do not nest properly and should only be declared in the main package scope.

This is because named subroutines are created at compile time so their lexical variables get assigned to the parent lexicals from the first execution of the parent block. If a parent scope is entered a second time, its lexicals are created again, while the nested subs still reference the old ones.

Anonymous subroutines get to capture each time you execute the sub operator, as they are created on the fly. If you are accustomed to using nested subroutines in other programming languages with their own private variables, you'll have to work at it a bit in Perl. The intuitive coding of this type of thing incurs mysterious warnings about "will not stay shared" due to the reasons explained above. For example, this won't work:

    sub outer {
        my $x = $_[0] + 35;
        sub inner { return $x * 19 }   # WRONG
        return $x + inner();

A work-around is the following:

    sub outer {
        my $x = $_[0] + 35;
        return $x + inner();

Now inner() can only be called from within outer(), because of the temporary assignments of the anonymous subroutine. But when it does, it has normal access to the lexical variable $x from the scope of outer() at the time outer is invoked.




    $x{ \$a } = $a;


    $r = \@a;
    $x{ $r } = $r;




Besides the obvious documents, source code can be instructive. Some pathological examples of the use of references can be found in the t/op/ref.t regression test in the Perl source directory.
