Plan 9 from Bell Labs’s /usr/web/sources/contrib/gabidiaz/root/sys/man/1perl/perlref

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  | will give a
.\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
.\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
.    de IX
.    tm Index:\\$1\t\\n%\t"\\$2"
..
.    nr % 0
.    rr F
.\}
.\"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLREF 1"
.TH PERLREF 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
perlref \- Perl references and nested data structures
.SH "NOTE"
.IX Header "NOTE"
This is complete documentation about all aspects of references.
For a shorter, tutorial introduction to just the essential features,
see perlreftut.
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
Before release 5 of Perl it was difficult to represent complex data
structures, because all references had to be symbolic\*(--and even then
it was difficult to refer to a variable instead of a symbol table entry.
Perl now not only makes it easier to use symbolic references to variables,
but also lets you have \*(L"hard\*(R" references to any piece of data or code.
Any scalar may hold a hard reference.  Because arrays and hashes contain
scalars, you can now easily build arrays of arrays, arrays of hashes,
hashes of arrays, arrays of hashes of functions, and so on.
.PP
Hard references are smart\*(--they keep track of reference counts for you,
automatically freeing the thing referred to when its reference count goes
to zero.  (Reference counts for values in self-referential or
cyclic data structures may not go to zero without a little help; see
\&\*(L"Two\-Phased Garbage Collection\*(R" in perlobj for a detailed explanation.)
If that thing happens to be an object, the object is destructed.  See
perlobj for more about objects.  (In a sense, everything in Perl is an
object, but we usually reserve the word for references to objects that
have been officially \*(L"blessed\*(R" into a class package.)
.PP
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 \f(CW*glob\fR notation is something of a symbolic reference.  (Symbolic
references are sometimes called \*(L"soft references\*(R", but please don't call
them that; references are confusing enough without useless synonyms.)
.PP
In contrast, hard references are more like hard links in a Unix file
system: They are used to access an underlying object without concern for
what its (other) name is.  When the word \*(L"reference\*(R" is used without an
adjective, as in the following paragraph, it is usually talking about a
hard reference.
.PP
References are easy to use in Perl.  There is just one overriding
principle: Perl does no implicit referencing or dereferencing.  When a
scalar is holding a reference, it always behaves as a simple scalar.  It
doesn't magically start being an array or hash or subroutine; you have to
tell it explicitly to do so, by dereferencing it.
.Sh "Making References"
.IX Subsection "Making References"
References can be created in several ways.
.IP "1." 4
By using the backslash operator on a variable, subroutine, or value.
(This works much like the & (address\-of) operator in C.)  
This typically creates \fIanother\fR 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:
.Sp
.Vb 5
\&    $scalarref = \e$foo;
\&    $arrayref  = \e@ARGV;
\&    $hashref   = \e%ENV;
\&    $coderef   = \e&handler;
\&    $globref   = \e*foo;
.Ve
.Sp
It isn't possible to create a true reference to an \s-1IO\s0 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 \f(CW*foo{THING}\fR syntax below.  However,
you can still use type globs and globrefs as though they were \s-1IO\s0 handles.
.IP "2." 4
A reference to an anonymous array can be created using square
brackets:
.Sp
.Vb 1
\&    $arrayref = [1, 2, ['a', 'b', 'c']];
.Ve
.Sp
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, \f(CW\*(C`$arrayref\->[2][1]\*(C'\fR would have
the value \*(L"b\*(R".)
.Sp
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!
.Sp
.Vb 2
\&    @list = (\e$a, \e@b, \e%c);
\&    @list = \e($a, @b, %c);      # same thing!
.Ve
.Sp
As a special case, \f(CW\*(C`\e(@foo)\*(C'\fR returns a list of references to the contents
of \f(CW@foo\fR, not a reference to \f(CW@foo\fR itself.  Likewise for \f(CW%foo\fR,
except that the key references are to copies (since the keys are just
strings rather than full-fledged scalars).
.IP "3." 4
A reference to an anonymous hash can be created using curly
brackets:
.Sp
.Vb 4
\&    $hashref = {
\&        'Adam'  => 'Eve',
\&        'Clyde' => 'Bonnie',
\&    };
.Ve
.Sp
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 \fIlocal()\fR or \fImy()\fR) are executable
statements, not compile-time declarations.
.Sp
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 \f(CW\*(C`+\*(C'\fR or a \f(CW\*(C`return\*(C'\fR in front so
that Perl realizes the opening brace isn't starting a \s-1BLOCK\s0.  The economy and
mnemonic value of using curlies is deemed worth this occasional extra
hassle.
.Sp
For example, if you wanted a function to make a new hash and return a
reference to it, you have these options:
.Sp
.Vb 3
\&    sub hashem {        { @_ } }   # silently wrong
\&    sub hashem {       +{ @_ } }   # ok
\&    sub hashem { return { @_ } }   # ok
.Ve
.Sp
On the other hand, if you want the other meaning, you can do this:
.Sp
.Vb 3
\&    sub showem {        { @_ } }   # ambiguous (currently ok, but may change)
\&    sub showem {       {; @_ } }   # ok
\&    sub showem { { return @_ } }   # ok
.Ve
.Sp
The leading \f(CW\*(C`+{\*(C'\fR and \f(CW\*(C`{;\*(C'\fR always serve to disambiguate
the expression to mean either the \s-1HASH\s0 reference, or the \s-1BLOCK\s0.
.IP "4." 4
A reference to an anonymous subroutine can be created by using
\&\f(CW\*(C`sub\*(C'\fR without a subname:
.Sp
.Vb 1
\&    $coderef = sub { print "Boink!\en" };
.Ve
.Sp
Note the semicolon.  Except for the code
inside not being immediately executed, a \f(CW\*(C`sub {}\*(C'\fR is not so much a
declaration as it is an operator, like \f(CW\*(C`do{}\*(C'\fR or \f(CW\*(C`eval{}\*(C'\fR.  (However, no
matter how many times you execute that particular line (unless you're in an
\&\f(CW\*(C`eval("...")\*(C'\fR), \f(CW$coderef\fR will still have a reference to the \fIsame\fR
anonymous subroutine.)
.Sp
Anonymous subroutines act as closures with respect to \fImy()\fR 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.
.Sp
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 perlobj.
.Sp
You might also think of closure as a way to write a subroutine
template without using \fIeval()\fR.  Here's a small example of how
closures work:
.Sp
.Vb 6
\&    sub newprint {
\&        my $x = shift;
\&        return sub { my $y = shift; print "$x, $y!\en"; };
\&    }
\&    $h = newprint("Howdy");
\&    $g = newprint("Greetings");
.Ve
.Sp
.Vb 1
\&    # Time passes...
.Ve
.Sp
.Vb 2
\&    &$h("world");
\&    &$g("earthlings");
.Ve
.Sp
This prints
.Sp
.Vb 2
\&    Howdy, world!
\&    Greetings, earthlings!
.Ve
.Sp
Note particularly that \f(CW$x\fR continues to refer to the value passed
into \fInewprint()\fR \fIdespite\fR \*(L"my \f(CW$x\fR\*(R" having gone out of scope by the
time the anonymous subroutine runs.  That's what a closure is all
about.
.Sp
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.
.IP "5." 4
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 \fInew()\fR and called indirectly:
.Sp
.Vb 1
\&    $objref = new Doggie (Tail => 'short', Ears => 'long');
.Ve
.Sp
But don't have to be:
.Sp
.Vb 1
\&    $objref   = Doggie->new(Tail => 'short', Ears => 'long');
.Ve
.Sp
.Vb 2
\&    use Term::Cap;
\&    $terminal = Term::Cap->Tgetent( { OSPEED => 9600 });
.Ve
.Sp
.Vb 4
\&    use Tk;
\&    $main    = MainWindow->new();
\&    $menubar = $main->Frame(-relief              => "raised",
\&                            -borderwidth         => 2)
.Ve
.IP "6." 4
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.
.IP "7." 4
A reference can be created by using a special syntax, lovingly known as
the *foo{\s-1THING\s0} syntax.  *foo{\s-1THING\s0} returns a reference to the \s-1THING\s0
slot in *foo (which is the symbol table entry which holds everything
known as foo).
.Sp
.Vb 6
\&    $scalarref = *foo{SCALAR};
\&    $arrayref  = *ARGV{ARRAY};
\&    $hashref   = *ENV{HASH};
\&    $coderef   = *handler{CODE};
\&    $ioref     = *STDIN{IO};
\&    $globref   = *foo{GLOB};
.Ve
.Sp
All of these are self-explanatory except for \f(CW*foo{IO}\fR.  It returns
the \s-1IO\s0 handle, used for file handles (\*(L"open\*(R" in perlfunc), sockets
(\*(L"socket\*(R" in perlfunc and \*(L"socketpair\*(R" in perlfunc), and directory
handles (\*(L"opendir\*(R" in perlfunc).  For compatibility with previous
versions of Perl, \f(CW*foo{FILEHANDLE}\fR is a synonym for \f(CW*foo{IO}\fR, though it
is deprecated as of 5.8.0.  If deprecation warnings are in effect, it will warn
of its use.
.Sp
\&\f(CW*foo{THING}\fR returns undef if that particular \s-1THING\s0 hasn't been used yet,
except in the case of scalars.  \f(CW*foo{SCALAR}\fR returns a reference to an
anonymous scalar if \f(CW$foo\fR hasn't been used yet.  This might change in a
future release.
.Sp
\&\f(CW*foo{IO}\fR is an alternative to the \f(CW*HANDLE\fR mechanism given in
\&\*(L"Typeglobs and Filehandles\*(R" 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.
.Sp
.Vb 2
\&    splutter(*STDOUT);          # pass the whole glob
\&    splutter(*STDOUT{IO});      # pass both file and dir handles
.Ve
.Sp
.Vb 4
\&    sub splutter {
\&        my $fh = shift;
\&        print $fh "her um well a hmmm\en";
\&    }
.Ve
.Sp
.Vb 2
\&    $rec = get_rec(*STDIN);     # pass the whole glob
\&    $rec = get_rec(*STDIN{IO}); # pass both file and dir handles
.Ve
.Sp
.Vb 4
\&    sub get_rec {
\&        my $fh = shift;
\&        return scalar <$fh>;
\&    }
.Ve
.Sh "Using References"
.IX Subsection "Using References"
That's it for creating references.  By now you're probably dying to
know how to use references to get back to your long-lost data.  There
are several basic methods.
.IP "1." 4
Anywhere you'd put an identifier (or chain of identifiers) as part
of a variable or subroutine name, you can replace the identifier with
a simple scalar variable containing a reference of the correct type:
.Sp
.Vb 6
\&    $bar = $$scalarref;
\&    push(@$arrayref, $filename);
\&    $$arrayref[0] = "January";
\&    $$hashref{"KEY"} = "VALUE";
\&    &$coderef(1,2,3);
\&    print $globref "output\en";
.Ve
.Sp
It's important to understand that we are specifically \fInot\fR dereferencing
\&\f(CW$arrayref[0]\fR or \f(CW$hashref{"KEY"}\fR there.  The dereference of the
scalar variable happens \fIbefore\fR it does any key lookups.  Anything more
complicated than a simple scalar variable must use methods 2 or 3 below.
However, a \*(L"simple scalar\*(R" includes an identifier that itself uses method
1 recursively.  Therefore, the following prints \*(L"howdy\*(R".
.Sp
.Vb 2
\&    $refrefref = \e\e\e"howdy";
\&    print $$$$refrefref;
.Ve
.IP "2." 4
Anywhere you'd put an identifier (or chain of identifiers) as part of a
variable or subroutine name, you can replace the identifier with a
\&\s-1BLOCK\s0 returning a reference of the correct type.  In other words, the
previous examples could be written like this:
.Sp
.Vb 6
\&    $bar = ${$scalarref};
\&    push(@{$arrayref}, $filename);
\&    ${$arrayref}[0] = "January";
\&    ${$hashref}{"KEY"} = "VALUE";
\&    &{$coderef}(1,2,3);
\&    $globref->print("output\en");  # iff IO::Handle is loaded
.Ve
.Sp
Admittedly, it's a little silly to use the curlies in this case, but
the \s-1BLOCK\s0 can contain any arbitrary expression, in particular,
subscripted expressions:
.Sp
.Vb 1
\&    &{ $dispatch{$index} }(1,2,3);      # call correct routine
.Ve
.Sp
Because of being able to omit the curlies for the simple case of \f(CW$$x\fR,
people often make the mistake of viewing the dereferencing symbols as
proper operators, and wonder about their precedence.  If they were,
though, you could use parentheses instead of braces.  That's not the case.
Consider the difference below; case 0 is a short-hand version of case 1,
\&\fInot\fR case 2:
.Sp
.Vb 4
\&    $$hashref{"KEY"}   = "VALUE";       # CASE 0
\&    ${$hashref}{"KEY"} = "VALUE";       # CASE 1
\&    ${$hashref{"KEY"}} = "VALUE";       # CASE 2
\&    ${$hashref->{"KEY"}} = "VALUE";     # CASE 3
.Ve
.Sp
Case 2 is also deceptive in that you're accessing a variable
called \f(CW%hashref\fR, not dereferencing through \f(CW$hashref\fR to the hash
it's presumably referencing.  That would be case 3.
.IP "3." 4
Subroutine calls and lookups of individual array elements arise often
enough that it gets cumbersome to use method 2.  As a form of
syntactic sugar, the examples for method 2 may be written:
.Sp
.Vb 3
\&    $arrayref->[0] = "January";   # Array element
\&    $hashref->{"KEY"} = "VALUE";  # Hash element
\&    $coderef->(1,2,3);            # Subroutine call
.Ve
.Sp
The left side of the arrow can be any expression returning a reference,
including a previous dereference.  Note that \f(CW$array[$x]\fR is \fInot\fR the
same thing as \f(CW\*(C`$array\->[$x]\*(C'\fR here:
.Sp
.Vb 1
\&    $array[$x]->{"foo"}->[0] = "January";
.Ve
.Sp
This is one of the cases we mentioned earlier in which references could
spring into existence when in an lvalue context.  Before this
statement, \f(CW$array[$x]\fR may have been undefined.  If so, it's
automatically defined with a hash reference so that we can look up
\&\f(CW\*(C`{"foo"}\*(C'\fR in it.  Likewise \f(CW\*(C`$array[$x]\->{"foo"}\*(C'\fR will automatically get
defined with an array reference so that we can look up \f(CW\*(C`[0]\*(C'\fR in it.
This process is called \fIautovivification\fR.
.Sp
One more thing here.  The arrow is optional \fIbetween\fR brackets
subscripts, so you can shrink the above down to
.Sp
.Vb 1
\&    $array[$x]{"foo"}[0] = "January";
.Ve
.Sp
Which, in the degenerate case of using only ordinary arrays, gives you
multidimensional arrays just like C's:
.Sp
.Vb 1
\&    $score[$x][$y][$z] += 42;
.Ve
.Sp
Well, okay, not entirely like C's arrays, actually.  C doesn't know how
to grow its arrays on demand.  Perl does.
.IP "4." 4
If a reference happens to be a reference to an object, then there are
probably methods to access the things referred to, and you should probably
stick to those methods unless you're in the class package that defines the
object's methods.  In other words, be nice, and don't violate the object's
encapsulation without a very good reason.  Perl does not enforce
encapsulation.  We are not totalitarians here.  We do expect some basic
civility though.
.PP
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.
.PP
.Vb 3
\&    if ($ref1 == $ref2) {  # cheap numeric compare of references
\&        print "refs 1 and 2 refer to the same thing\en";
\&    }
.Ve
.PP
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 \fIref()\fR operator returns
just the type of thing the reference is pointing to, without the
address.  See \*(L"ref\*(R" in perlfunc for details and examples of its use.
.PP
The \fIbless()\fR operator may be used to associate the object a reference
points to with a package functioning as an object class.  See perlobj.
.PP
A typeglob may be dereferenced the same way a reference can, because
the dereference syntax always indicates the type of reference desired.
So \f(CW\*(C`${*foo}\*(C'\fR and \f(CW\*(C`${\e$foo}\*(C'\fR both indicate the same scalar variable.
.PP
Here's a trick for interpolating a subroutine call into a string:
.PP
.Vb 1
\&    print "My sub returned @{[mysub(1,2,3)]} that time.\en";
.Ve
.PP
The way it works is that when the \f(CW\*(C`@{...}\*(C'\fR is seen in the double-quoted
string, it's evaluated as a block.  The block creates a reference to an
anonymous array containing the results of the call to \f(CW\*(C`mysub(1,2,3)\*(C'\fR.  So
the whole block returns a reference to an array, which is then
dereferenced by \f(CW\*(C`@{...}\*(C'\fR and stuck into the double-quoted string. This
chicanery is also useful for arbitrary expressions:
.PP
.Vb 1
\&    print "That yields @{[$n + 5]} widgets\en";
.Ve
.Sh "Symbolic references"
.IX Subsection "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 \fIisn't\fR 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 \fIname\fR
of a variable, rather than a direct link to a (possibly) anonymous
value.
.PP
People frequently expect it to work like this.  So it does.
.PP
.Vb 9
\&    $name = "foo";
\&    $$name = 1;                 # Sets $foo
\&    ${$name} = 2;               # Sets $foo
\&    ${$name x 2} = 3;           # Sets $foofoo
\&    $name->[0] = 4;             # Sets $foo[0]
\&    @$name = ();                # Clears @foo
\&    &$name();                   # Calls &foo() (as in Perl 4)
\&    $pack = "THAT";
\&    ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
.Ve
.PP
This is powerful, and slightly dangerous, in that it's possible
to intend (with the utmost sincerity) to use a hard reference, and
accidentally use a symbolic reference instead.  To protect against
that, you can say
.PP
.Vb 1
\&    use strict 'refs';
.Ve
.PP
and then only hard references will be allowed for the rest of the enclosing
block.  An inner block may countermand that with
.PP
.Vb 1
\&    no strict 'refs';
.Ve
.PP
Only package variables (globals, even if localized) are visible to
symbolic references.  Lexical variables (declared with \fImy()\fR) aren't in
a symbol table, and thus are invisible to this mechanism.  For example:
.PP
.Vb 6
\&    local $value = 10;
\&    $ref = "value";
\&    {
\&        my $value = 20;
\&        print $$ref;
\&    }
.Ve
.PP
This will still print 10, not 20.  Remember that \fIlocal()\fR affects package
variables, which are all \*(L"global\*(R" to the package.
.Sh "Not-so-symbolic references"
.IX Subsection "Not-so-symbolic references"
A new feature contributing to readability in perl version 5.001 is that the
brackets around a symbolic reference behave more like quotes, just as they
always have within a string.  That is,
.PP
.Vb 2
\&    $push = "pop on ";
\&    print "${push}over";
.Ve
.PP
has always meant to print \*(L"pop on over\*(R", even though push is
a reserved word.  This has been generalized to work the same outside
of quotes, so that
.PP
.Vb 1
\&    print ${push} . "over";
.Ve
.PP
and even
.PP
.Vb 1
\&    print ${ push } . "over";
.Ve
.PP
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 \fInot\fR considered to be a symbolic reference when you're
using strict refs:
.PP
.Vb 3
\&    use strict 'refs';
\&    ${ bareword };      # Okay, means $bareword.
\&    ${ "bareword" };    # Error, symbolic reference.
.Ve
.PP
Similarly, because of all the subscripting that is done using single
words, we've applied the same rule to any bareword that is used for
subscripting a hash.  So now, instead of writing
.PP
.Vb 1
\&    $array{ "aaa" }{ "bbb" }{ "ccc" }
.Ve
.PP
you can write just
.PP
.Vb 1
\&    $array{ aaa }{ bbb }{ ccc }
.Ve
.PP
and not worry about whether the subscripts are reserved words.  In the
rare event that you do wish to do something like
.PP
.Vb 1
\&    $array{ shift }
.Ve
.PP
you can force interpretation as a reserved word by adding anything that
makes it more than a bareword:
.PP
.Vb 3
\&    $array{ shift() }
\&    $array{ +shift }
\&    $array{ shift @_ }
.Ve
.PP
The \f(CW\*(C`use warnings\*(C'\fR pragma or the \fB\-w\fR 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.
.Sh "Pseudo\-hashes: Using an array as a hash"
.IX Subsection "Pseudo-hashes: Using an array as a hash"
\&\fB\s-1WARNING\s0\fR:  This section describes an experimental feature.  Details may
change without notice in future versions.
.PP
\&\fB\s-1NOTE\s0\fR: The current user-visible implementation of pseudo-hashes
(the weird use of the first array element) is deprecated starting from
Perl 5.8.0 and will be removed in Perl 5.10.0, and the feature will be
implemented differently.  Not only is the current interface rather ugly,
but the current implementation slows down normal array and hash use quite
noticeably.  The 'fields' pragma interface will remain available.
.PP
Beginning with release 5.005 of Perl, you may use an array reference
in some contexts that would normally require a hash reference.  This
allows you to access array elements using symbolic names, as if they
were fields in a structure.
.PP
For this to work, the array must contain extra information.  The first
element of the array has to be a hash reference that maps field names
to array indices.  Here is an example:
.PP
.Vb 1
\&    $struct = [{foo => 1, bar => 2}, "FOO", "BAR"];
.Ve
.PP
.Vb 2
\&    $struct->{foo};  # same as $struct->[1], i.e. "FOO"
\&    $struct->{bar};  # same as $struct->[2], i.e. "BAR"
.Ve
.PP
.Vb 2
\&    keys %$struct;   # will return ("foo", "bar") in some order
\&    values %$struct; # will return ("FOO", "BAR") in same some order
.Ve
.PP
.Vb 3
\&    while (my($k,$v) = each %$struct) {
\&       print "$k => $v\en";
\&    }
.Ve
.PP
Perl will raise an exception if you try to access nonexistent fields.
To avoid inconsistencies, always use the \fIfields::phash()\fR function
provided by the \f(CW\*(C`fields\*(C'\fR pragma.
.PP
.Vb 2
\&    use fields;
\&    $pseudohash = fields::phash(foo => "FOO", bar => "BAR");
.Ve
.PP
For better performance, Perl can also do the translation from field
names to array indices at compile time for typed object references.
See fields.
.PP
There are two ways to check for the existence of a key in a
pseudo\-hash.  The first is to use \fIexists()\fR.  This checks to see if the
given field has ever been set.  It acts this way to match the behavior
of a regular hash.  For instance:
.PP
.Vb 3
\&    use fields;
\&    $phash = fields::phash([qw(foo bar pants)], ['FOO']);
\&    $phash->{pants} = undef;
.Ve
.PP
.Vb 3
\&    print exists $phash->{foo};    # true, 'foo' was set in the declaration
\&    print exists $phash->{bar};    # false, 'bar' has not been used.
\&    print exists $phash->{pants};  # true, your 'pants' have been touched
.Ve
.PP
The second is to use \fIexists()\fR on the hash reference sitting in the
first array element.  This checks to see if the given key is a valid
field in the pseudo\-hash.
.PP
.Vb 2
\&    print exists $phash->[0]{bar};      # true, 'bar' is a valid field
\&    print exists $phash->[0]{shoes};# false, 'shoes' can't be used
.Ve
.PP
\&\fIdelete()\fR on a pseudo-hash element only deletes the value corresponding
to the key, not the key itself.  To delete the key, you'll have to
explicitly delete it from the first hash element.
.PP
.Vb 5
\&    print delete $phash->{foo};     # prints $phash->[1], "FOO"
\&    print exists $phash->{foo};     # false
\&    print exists $phash->[0]{foo};  # true, key still exists
\&    print delete $phash->[0]{foo};  # now key is gone
\&    print $phash->{foo};            # runtime exception
.Ve
.Sh "Function Templates"
.IX Subsection "Function Templates"
As explained above, a closure is an anonymous function with access to the
lexical variables visible when that function was compiled.  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.
.PP
Using a closure as a function template allows us to generate many functions
that act similarly.  Suppose you wanted functions named after the colors
that generated \s-1HTML\s0 font changes for the various colors:
.PP
.Vb 1
\&    print "Be ", red("careful"), "with that ", green("light");
.Ve
.PP
The \fIred()\fR and \fIgreen()\fR 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.  
.PP
.Vb 5
\&    @colors = qw(red blue green yellow orange purple violet);
\&    for my $name (@colors) {
\&        no strict 'refs';       # allow symbol table manipulation
\&        *$name = *{uc $name} = sub { "<FONT COLOR='$name'>@_</FONT>" };
\&    }
.Ve
.PP
Now all those different functions appear to exist independently.  You can
call \fIred()\fR, \s-1\fIRED\s0()\fR, \fIblue()\fR, \s-1\fIBLUE\s0()\fR, \fIgreen()\fR, etc.  This technique saves on
both compile time and memory use, and is less error-prone as well, since
syntax checks happen at compile time.  It's critical that any variables in
the anonymous subroutine be lexicals in order to create a proper closure.
That's the reasons for the \f(CW\*(C`my\*(C'\fR on the loop iteration variable.
.PP
This is one of the only places where giving a prototype to a closure makes
much sense.  If you wanted to impose scalar context on the arguments of
these functions (probably not a wise idea for this particular example),
you could have written it this way instead:
.PP
.Vb 1
\&    *$name = sub ($) { "<FONT COLOR='$name'>$_[0]</FONT>" };
.Ve
.PP
However, since prototype checking happens at compile time, the assignment
above happens too late to be of much use.  You could address this by
putting the whole loop of assignments within a \s-1BEGIN\s0 block, forcing it
to occur during compilation.
.PP
Access to lexicals that change over type\*(--like those in the \f(CW\*(C`for\*(C'\fR loop
above\*(--only works with closures, not general subroutines.  In the general
case, then, named subroutines do not nest properly, although anonymous
ones do.  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''.  For example,
this won't work:
.PP
.Vb 5
\&    sub outer {
\&        my $x = $_[0] + 35;
\&        sub inner { return $x * 19 }   # WRONG
\&        return $x + inner();
\&    }
.Ve
.PP
A work-around is the following:
.PP
.Vb 5
\&    sub outer {
\&        my $x = $_[0] + 35;
\&        local *inner = sub { return $x * 19 };
\&        return $x + inner();
\&    }
.Ve
.PP
Now \fIinner()\fR can only be called from within \fIouter()\fR, because of the
temporary assignments of the closure (anonymous subroutine).  But when
it does, it has normal access to the lexical variable \f(CW$x\fR from the scope
of \fIouter()\fR.
.PP
This has the interesting effect of creating a function local to another
function, something not normally supported in Perl.
.SH "WARNING"
.IX Header "WARNING"
You may not (usefully) use a reference as the key to a hash.  It will be
converted into a string:
.PP
.Vb 1
\&    $x{ \e$a } = $a;
.Ve
.PP
If you try to dereference the key, it won't do a hard dereference, and
you won't accomplish what you're attempting.  You might want to do something
more like
.PP
.Vb 2
\&    $r = \e@a;
\&    $x{ $r } = $r;
.Ve
.PP
And then at least you can use the \fIvalues()\fR, which will be
real refs, instead of the \fIkeys()\fR, which won't.
.PP
The standard Tie::RefHash module provides a convenient workaround to this.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
Besides the obvious documents, source code can be instructive.
Some pathological examples of the use of references can be found
in the \fIt/op/ref.t\fR regression test in the Perl source directory.
.PP
See also perldsc and perllol for how to use references to create
complex data structures, and perltoot, perlobj, and perlbot
for how to use them to create objects.

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.