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

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 "PERLREFTUT 1"
.TH PERLREFTUT 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
perlreftut \- Mark's very short tutorial about references
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
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.
.PP
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%.
.SH "Who Needs Complicated Data Structures?"
.IX Header "Who Needs Complicated Data Structures?"
One problem that came up all the time in Perl 4 was how to represent a
hash whose values were lists.  Perl 4 had hashes, of course, but the
values had to be scalars; they couldn't be lists.  
.PP
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:
.PP
.Vb 6
\&        Chicago, USA
\&        Frankfurt, Germany
\&        Berlin, Germany
\&        Washington, USA
\&        Helsinki, Finland
\&        New York, USA
.Ve
.PP
and you want to produce an output like this, with each country mentioned
once, and then an alphabetical list of the cities in that country:
.PP
.Vb 3
\&        Finland: Helsinki.
\&        Germany: Berlin, Frankfurt.
\&        USA:  Chicago, New York, Washington.
.Ve
.PP
The natural way to do this is to have a hash whose keys are country
names.  Associated with each country name key is a list of the cities in
that country.  Each time you read a line of input, split it into a country
and a city, look up the list of cities already known to be in that
country, and append the new city to the list.  When you're done reading
the input, iterate over the hash as usual, sorting each list of cities
before you print it out.
.PP
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.
.SH "The Solution"
.IX Header "The Solution"
By the time Perl 5 rolled around, we were already stuck with this
design: Hash values must be scalars.  The solution to this is
references.
.PP
A reference is a scalar value that \fIrefers to\fR 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
of the United States: 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 \*(L"George Bush\*(R".
.PP
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 \*(L"George Bush\*(R", 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.
.PP
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.
.PP
We'll come back to this city-country problem later, after we've seen
some syntax for managing references.
.SH "Syntax"
.IX Header "Syntax"
There are just two ways to make a reference, and just two ways to use
it once you have it.
.Sh "Making References"
.IX Subsection "Making References"
\&\fBMake Rule 1\fR
.PP
If you put a \f(CW\*(C`\e\*(C'\fR in front of a variable, you get a
reference to that variable.
.PP
.Vb 2
\&    $aref = \e@array;         # $aref now holds a reference to @array
\&    $href = \e%hash;          # $href now holds a reference to %hash
.Ve
.PP
Once the reference is stored in a variable like \f(CW$aref\fR or \f(CW$href\fR, you
can copy it or store it just the same as any other scalar value:
.PP
.Vb 3
\&    $xy = $aref;             # $xy now holds a reference to @array
\&    $p[3] = $href;           # $p[3] now holds a reference to %hash
\&    $z = $p[3];              # $z now holds a reference to %hash
.Ve
.PP
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 \f(CW"\en"\fR or the number 80 without having to store it in a named
variable first.
.PP
\&\fBMake Rule 2\fR
.PP
\&\f(CW\*(C`[ ITEMS ]\*(C'\fR makes a new, anonymous array, and returns a reference to
that array. \f(CW\*(C`{ ITEMS }\*(C'\fR makes a new, anonymous hash. and returns a
reference to that hash.
.PP
.Vb 2
\&    $aref = [ 1, "foo", undef, 13 ];  
\&    # $aref now holds a reference to an array
.Ve
.PP
.Vb 2
\&    $href = { APR => 4, AUG => 8 };   
\&    # $href now holds a reference to a hash
.Ve
.PP
The references you get from rule 2 are the same kind of
references that you get from rule 1:
.PP
.Vb 2
\&        # This:
\&        $aref = [ 1, 2, 3 ];
.Ve
.PP
.Vb 3
\&        # Does the same as this:
\&        @array = (1, 2, 3);
\&        $aref = \e@array;
.Ve
.PP
The first line is an abbreviation for the following two lines, except
that it doesn't create the superfluous array variable \f(CW@array\fR.
.Sh "Using References"
.IX Subsection "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:
.PP
\&\fBUse Rule 1\fR
.PP
If \f(CW$aref\fR contains a reference to an array, then you
can put \f(CW\*(C`{$aref}\*(C'\fR anywhere you would normally put the name of an
array.  For example, \f(CW\*(C`@{$aref}\*(C'\fR instead of \f(CW@array\fR.
.PP
Here are some examples of that:
.PP
Arrays:
.PP
.Vb 4
\&        @a              @{$aref}                An array
\&        reverse @a      reverse @{$aref}        Reverse the array
\&        $a[3]           ${$aref}[3]             An element of the array
\&        $a[3] = 17;     ${$aref}[3] = 17        Assigning an element
.Ve
.PP
On each line are two expressions that do the same thing.  The
left-hand versions operate on the array \f(CW@a\fR, and the right-hand
versions operate on the array that is referred to by \f(CW$aref\fR, but
once they find the array they're operating on, they do the same things
to the arrays.
.PP
Using a hash reference is \fIexactly\fR the same:
.PP
.Vb 4
\&        %h              %{$href}              A hash
\&        keys %h         keys %{$href}         Get the keys from the hash
\&        $h{'red'}       ${$href}{'red'}       An element of the hash
\&        $h{'red'} = 17  ${$href}{'red'} = 17  Assigning an element
.Ve
.PP
\&\fBUse Rule 2\fR
.PP
\&\f(CW\*(C`${$aref}[3]\*(C'\fR is too hard to read, so you can write \f(CW\*(C`$aref\->[3]\*(C'\fR
instead.
.PP
\&\f(CW\*(C`${$href}{red}\*(C'\fR is too hard to read, so you can write
\&\f(CW\*(C`$href\->{red}\*(C'\fR instead.
.PP
Most often, when you have an array or a hash, you want to get or set a
single element from it.  \f(CW\*(C`${$aref}[3]\*(C'\fR and \f(CW\*(C`${$href}{'red'}\*(C'\fR have
too much punctuation, and Perl lets you abbreviate.
.PP
If \f(CW$aref\fR holds a reference to an array, then \f(CW\*(C`$aref\->[3]\*(C'\fR is
the fourth element of the array.  Don't confuse this with \f(CW$aref[3]\fR,
which is the fourth element of a totally different array, one
deceptively named \f(CW@aref\fR.  \f(CW$aref\fR and \f(CW@aref\fR are unrelated the
same way that \f(CW$item\fR and \f(CW@item\fR are.
.PP
Similarly, \f(CW\*(C`$href\->{'red'}\*(C'\fR is part of the hash referred to by
the scalar variable \f(CW$href\fR, perhaps even one with no name.
\&\f(CW$href{'red'}\fR is part of the deceptively named \f(CW%href\fR hash.  It's
easy to forget to leave out the \f(CW\*(C`\->\*(C'\fR, 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.
.SH "An Example"
.IX Header "An Example"
Let's see a quick example of how all this is useful.
.PP
First, remember that \f(CW\*(C`[1, 2, 3]\*(C'\fR makes an anonymous array containing
\&\f(CW\*(C`(1, 2, 3)\*(C'\fR, and gives you a reference to that array.
.PP
Now think about
.PP
.Vb 4
\&        @a = ( [1, 2, 3],
\&               [4, 5, 6],
\&               [7, 8, 9]
\&             );
.Ve
.PP
@a is an array with three elements, and each one is a reference to
another array.
.PP
\&\f(CW$a[1]\fR is one of these references.  It refers to an array, the array
containing \f(CW\*(C`(4, 5, 6)\*(C'\fR, and because it is a reference to an array,
\&\fB\s-1USE\s0 \s-1RULE\s0 2\fR says that we can write \f(CW$a[1]\->[2]\fR to get the
third element from that array.  \f(CW$a[1]\->[2]\fR is the 6.
Similarly, \f(CW$a[0]\->[1]\fR is the 2.  What we have here is like a
two-dimensional array; you can write \f(CW$a[ROW]\->[COLUMN]\fR to get
or set the element in any row and any column of the array.
.PP
The notation still looks a little cumbersome, so there's one more
abbreviation:  
.SH "Arrow Rule"
.IX Header "Arrow Rule"
In between two \fBsubscripts\fR, the arrow is optional.
.PP
Instead of \f(CW$a[1]\->[2]\fR, we can write \f(CW$a[1][2]\fR; it means the
same thing.  Instead of \f(CW$a[0]\->[1]\fR, we can write \f(CW$a[0][1]\fR;
it means the same thing.
.PP
Now it really looks like two-dimensional arrays!
.PP
You can see why the arrows are important.  Without them, we would have
had to write \f(CW\*(C`${$a[1]}[2]\*(C'\fR instead of \f(CW$a[1][2]\fR.  For
three-dimensional arrays, they let us write \f(CW$x[2][3][5]\fR instead of
the unreadable \f(CW\*(C`${${$x[2]}[3]}[5]\*(C'\fR.
.SH "Solution"
.IX Header "Solution"
Here's the answer to the problem I posed earlier, of reformatting a
file of city and country names.
.PP
.Vb 12
\&    1   while (<>) {
\&    2     chomp;
\&    3     my ($city, $country) = split /, /;
\&    4     push @{$table{$country}}, $city;
\&    5   }
\&    6
\&    7   foreach $country (sort keys %table) {
\&    8     print "$country: ";
\&    9     my @cities = @{$table{$country}};
\&   10     print join ', ', sort @cities;
\&   11     print ".\en";
\&   12   }
.Ve
.PP
The program has two pieces:  Lines 1\-\-5 read the input and build a
data structure, and lines 7\-\-12 analyze the data and print out the
report.  
.PP
In the first part, line 4 is the important one.  We're going to have a
hash, \f(CW%table\fR, whose keys are country names, and whose values are
(references to) arrays of city names.  After acquiring a city and
country name, the program looks up \f(CW$table{$country}\fR, which holds (a
reference to) the list of cities seen in that country so far.  Line 4 is
totally analogous to
.PP
.Vb 1
\&        push @array, $city;
.Ve
.PP
except that the name \f(CW\*(C`array\*(C'\fR has been replaced by the reference
\&\f(CW\*(C`{$table{$country}}\*(C'\fR.  The \f(CW\*(C`push\*(C'\fR adds a city name to the end of the
referred-to array.
.PP
In the second part, line 9 is the important one.  Again,
\&\f(CW$table{$country}\fR is (a reference to) the list of cities in the country, so
we can recover the original list, and copy it into the array \f(CW@cities\fR,
by using \f(CW\*(C`@{$table{$country}}\*(C'\fR.  Line 9 is totally analogous to
.PP
.Vb 1
\&        @cities = @array;
.Ve
.PP
except that the name \f(CW\*(C`array\*(C'\fR has been replaced by the reference
\&\f(CW\*(C`{$table{$country}}\*(C'\fR.  The \f(CW\*(C`@\*(C'\fR tells Perl to get the entire array.
.PP
The rest of the program is just familiar uses of \f(CW\*(C`chomp\*(C'\fR, \f(CW\*(C`split\*(C'\fR, \f(CW\*(C`sort\*(C'\fR,
\&\f(CW\*(C`print\*(C'\fR, and doesn't involve references at all.
.PP
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, \f(CW$country\fR is \f(CW'Greece'\fR, and \f(CW$city\fR is
\&\f(CW'Athens'\fR.  Since this is the first city in Greece,
\&\f(CW$table{$country}\fR is undefined\-\-\-in fact there isn't an \f(CW'Greece'\fR key
in \f(CW%table\fR at all.  What does line 4 do here?
.PP
.Vb 1
\& 4      push @{$table{$country}}, $city;
.Ve
.PP
This is Perl, so it does the exact right thing.  It sees that you want
to push \f(CW\*(C`Athens\*(C'\fR 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 \f(CW\*(C`Athens\*(C'\fR onto it.  This is called `autovivification'.
.SH "The Rest"
.IX Header "The Rest"
I promised to give you 90% of the benefit with 10% of the details, and
that means I left out 90% of the details.  Now that you have an
overview of the important parts, it should be easier to read the
perlref manual page, which discusses 100% of the details.
.PP
Some of the highlights of perlref:
.IP "\(bu" 4
You can make references to anything, including scalars, functions, and
other references.
.IP "\(bu" 4
In \fB\s-1USE\s0 \s-1RULE\s0 1\fR, you can omit the curly brackets whenever the thing
inside them is an atomic scalar variable like \f(CW$aref\fR.  For example,
\&\f(CW@$aref\fR is the same as \f(CW\*(C`@{$aref}\*(C'\fR, and \f(CW$$aref[1]\fR is the same as
\&\f(CW\*(C`${$aref}[1]\*(C'\fR.  If you're just starting out, you may want to adopt
the habit of always including the curly brackets.
.IP "\(bu" 4
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 \s-1HASH\s0 for hash references and
\&\s-1ARRAY\s0 for array references.
.IP "\(bu" 4
If you try to use a reference like a string, you get strings like
.Sp
.Vb 1
\&        ARRAY(0x80f5dec)   or    HASH(0x826afc0)
.Ve
.Sp
If you ever see a string that looks like this, you'll know you
printed out a reference by mistake.
.Sp
A side effect of this representation is that you can use \f(CW\*(C`eq\*(C'\fR to see
if two references refer to the same thing.  (But you should usually use
\&\f(CW\*(C`==\*(C'\fR instead because it's much faster.)
.IP "\(bu" 4
You can use a string as if it were a reference.  If you use the string
\&\f(CW"foo"\fR as an array reference, it's taken to be a reference to the
array \f(CW@foo\fR.  This is called a \fIsoft reference\fR or \fIsymbolic reference\fR.
.PP
You might prefer to go on to perllol instead of perlref; it
discusses lists of lists and multidimensional arrays in detail.  After
that, you should move on to perldsc; 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.
.SH "Summary"
.IX Header "Summary"
Everyone needs compound data structures, and in Perl the way you get
them is with references.  There are four important rules for managing
references: Two for making references and two for using them.  Once
you know these rules you can do most of the important things you need
to do with references.
.SH "Credits"
.IX Header "Credits"
Author: Mark-Jason Dominus, Plover Systems (\f(CW\*(C`mjd\-perl\-ref+@plover.com\*(C'\fR)
.PP
This article originally appeared in \fIThe Perl Journal\fR
( http://www.tpj.com/ ) volume 3, #2.  Reprinted with permission.  
.PP
The original title was \fIUnderstand References Today\fR.
.Sh "Distribution Conditions"
.IX Subsection "Distribution Conditions"
Copyright 1998 The Perl Journal.
.PP
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.
.PP
Irrespective of its distribution, all code examples in these files are
hereby placed into the public domain.  You are permitted and
encouraged to use this code in your own programs for fun or for profit
as you see fit.  A simple comment in the code giving credit would be
courteous but is not required.

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.