- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

15.2 Making References

References can be created in several ways.

  1. @cindex \ 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;
    It isn't possible to create a true reference to an IO handle (filehandle or dirhandle) using the backslash operator. The most you can get is a reference to a typeglob, which is actually a complete symbol table entry. But see the explanation of the *foo{THING} syntax below. However, you can still use type globs and globrefs as though they were IO handles.
  2. @cindex array, anonymous A reference to an anonymous array can be created using square brackets:
    $arrayref = [1, 2, ['a', 'b', 'c']];
    Here we've created a reference to an anonymous array of three elements whose final element is itself a reference to another anonymous array of three elements. (The multidimensional syntax described later can be used to access this. For example, after the above, $arrayref->[2][1] would have the value "b".) Taking a reference to an enumerated list is not the same as using square brackets--instead it's the same as creating a list of references!
    @list = (\$a, \@b, \%c);
    @list = \($a, @b, %c);      # same thing!
    As a special case, \(@foo) returns a list of references to the contents of @foo, not a reference to @foo itself. Likewise for %foo, except that the key references are to copies (since the keys are just strings rather than full-fledged scalars).
  3. @cindex hash, anonymous A reference to an anonymous hash can be created using curly brackets:
    $hashref = {
        'Adam'  => 'Eve',
        'Clyde' => 'Bonnie',
    Anonymous hash and array composers like these can be intermixed freely to produce as complicated a structure as you want. The multidimensional syntax described below works for these too. The values above are literals, but variables and expressions would work just as well, because assignment operators in Perl (even within local() or my()) are executable statements, not compile-time declarations. Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a + or a return in front so that Perl realizes the opening brace isn't starting a BLOCK. The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle. For example, if you wanted a function to make a new hash and return a reference to it, you have these options:
    sub hashem {        { @_ } }   # silently wrong
    sub hashem {       +{ @_ } }   # ok
    sub hashem { return { @_ } }   # ok
    On the other hand, if you want the other meaning, you can do this:
    sub showem {        { @_ } }   # ambiguous (currently ok, 
                                                       but may change)
    sub showem {       {; @_ } }   # ok
    sub showem { { return @_ } }   # ok
    The leading +{ and {; always serve to disambiguate the expression to mean either the HASH reference, or the BLOCK.
  4. @cindex subroutine, anonymous A reference to an anonymous subroutine can be created by using sub without a subname:
    $coderef = sub { print "Boink!\n" };
    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. In human terms, it's a funny way of passing arguments to a subroutine when you define it as well as when you call it. It's useful for setting up little bits of code to run later, such as callbacks. You can even do object-oriented stuff with it, though Perl already provides a different mechanism to do that--see 16. 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;
        return sub { my $y = shift; print "$x, $y!\n"; };
    $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. This applies only to lexical variables, by the way. Dynamic variables continue to work as they have always worked. Closure is not something that most Perl programmers need trouble themselves about to begin with.
  5. @cindex constructor 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:
    $objref = new Doggie( Tail => 'short', Ears => 'long' );
    But that can produce ambiguous syntax in certain cases, so it's often better to use the direct method invocation approach:
    $objref   = Doggie->new(Tail => 'short', Ears => 'long');
    use Term::Cap;
    $terminal = Term::Cap->Tgetent( { OSPEED => 9600 });
    use Tk;
    $main    = MainWindow->new();
    $menubar = $main->Frame(-relief              => "raised",
                            -borderwidth         => 2)
  6. @cindex autovivification References of the appropriate type can spring into existence if you dereference them in a context that assumes they exist. Because we haven't talked about dereferencing yet, we can't show you any examples yet.
  7. @cindex *foo{THING} A reference can be created by using a special syntax, lovingly known as the *foo{THING} syntax. *foo{THING} returns a reference to the THING slot in *foo (which is the symbol table entry which holds everything known as foo).
    $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 ( ), sockets ( and ), and directory handles ( ). 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{THING} returns undef if that particular THING hasn't been used yet, except in the case of scalars. *foo{SCALAR} returns a reference to an anonymous scalar if $foo hasn't been used yet. This might change in a future release. *foo{IO} is an alternative to the *HANDLE mechanism given in 5.8 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;
        print $fh "her um well a hmmm\n";
    $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>;
ISBN 9781906966027Perl Language Reference ManualSee the print edition