1PERLREFTUT(1)          Perl Programmers Reference Guide          PERLREFTUT(1)
2
3
4

NAME

6       perlreftut - Mark's very short tutorial about references
7

DESCRIPTION

9       One of the most important new features in Perl 5 was the capability to
10       manage complicated data structures like multidimensional arrays and
11       nested hashes.  To enable these, Perl 5 introduced a feature called
12       references, and using references is the key to managing complicated,
13       structured data in Perl.  Unfortunately, there's a lot of funny syntax
14       to learn, and the main manual page can be hard to follow.  The manual
15       is quite complete, and sometimes people find that a problem, because it
16       can be hard to tell what is important and what isn't.
17
18       Fortunately, you only need to know 10% of what's in the main page to
19       get 90% of the benefit.  This page will show you that 10%.
20

Who Needs Complicated Data Structures?

22       One problem that comes up all the time is needing a hash whose values
23       are lists.  Perl has hashes, of course, but the values have to be
24       scalars; they can't be lists.
25
26       Why would you want a hash of lists?  Let's take a simple example: You
27       have a file of city and country names, like this:
28
29               Chicago, USA
30               Frankfurt, Germany
31               Berlin, Germany
32               Washington, USA
33               Helsinki, Finland
34               New York, USA
35
36       and you want to produce an output like this, with each country
37       mentioned once, and then an alphabetical list of the cities in that
38       country:
39
40               Finland: Helsinki.
41               Germany: Berlin, Frankfurt.
42               USA:  Chicago, New York, Washington.
43
44       The natural way to do this is to have a hash whose keys are country
45       names.  Associated with each country name key is a list of the cities
46       in that country.  Each time you read a line of input, split it into a
47       country and a city, look up the list of cities already known to be in
48       that country, and append the new city to the list.  When you're done
49       reading the input, iterate over the hash as usual, sorting each list of
50       cities before you print it out.
51
52       If hash values couldn't be lists, you lose.  You'd probably have to
53       combine all the cities into a single string somehow, and then when time
54       came to write the output, you'd have to break the string into a list,
55       sort the list, and turn it back into a string.  This is messy and
56       error-prone.  And it's frustrating, because Perl already has perfectly
57       good lists that would solve the problem if only you could use them.
58

The Solution

60       By the time Perl 5 rolled around, we were already stuck with this
61       design: Hash values must be scalars.  The solution to this is
62       references.
63
64       A reference is a scalar value that refers to an entire array or an
65       entire hash (or to just about anything else).  Names are one kind of
66       reference that you're already familiar with.  Each human being is a
67       messy, inconvenient collection of cells. But to refer to a particular
68       human, for instance the first computer programmer, it isn't necessary
69       to describe each of their cells; all you need is the easy, convenient
70       scalar string "Ada Lovelace".
71
72       References in Perl are like names for arrays and hashes.  They're
73       Perl's private, internal names, so you can be sure they're unambiguous.
74       Unlike a human name, a reference only refers to one thing, and you
75       always know what it refers to.  If you have a reference to an array,
76       you can recover the entire array from it.  If you have a reference to a
77       hash, you can recover the entire hash.  But the reference is still an
78       easy, compact scalar value.
79
80       You can't have a hash whose values are arrays; hash values can only be
81       scalars.  We're stuck with that.  But a single reference can refer to
82       an entire array, and references are scalars, so you can have a hash of
83       references to arrays, and it'll act a lot like a hash of arrays, and
84       it'll be just as useful as a hash of arrays.
85
86       We'll come back to this city-country problem later, after we've seen
87       some syntax for managing references.
88

Syntax

90       There are just two ways to make a reference, and just two ways to use
91       it once you have it.
92
93   Making References
94       Make Rule 1
95
96       If you put a "\" in front of a variable, you get a reference to that
97       variable.
98
99           $aref = \@array;         # $aref now holds a reference to @array
100           $href = \%hash;          # $href now holds a reference to %hash
101
102       Once the reference is stored in a variable like $aref or $href, you can
103       copy it or store it just the same as any other scalar value:
104
105           $xy = $aref;             # $xy now holds a reference to @array
106           $p[3] = $href;           # $p[3] now holds a reference to %hash
107           $z = $p[3];              # $z now holds a reference to %hash
108
109       These examples show how to make references to variables with names.
110       Sometimes you want to make an array or a hash that doesn't have a name.
111       This is analogous to the way you like to be able to use the string "\n"
112       or the number 80 without having to store it in a named variable first.
113
114       Make Rule 2
115
116       "[ ITEMS ]" makes a new, anonymous array, and returns a reference to
117       that array.  "{ ITEMS }" makes a new, anonymous hash, and returns a
118       reference to that hash.
119
120           $aref = [ 1, "foo", undef, 13 ];
121           # $aref now holds a reference to an array
122
123           $href = { APR => 4, AUG => 8 };
124           # $href now holds a reference to a hash
125
126       The references you get from rule 2 are the same kind of references that
127       you get from rule 1:
128
129               # This:
130               $aref = [ 1, 2, 3 ];
131
132               # Does the same as this:
133               @array = (1, 2, 3);
134               $aref = \@array;
135
136       The first line is an abbreviation for the following two lines, except
137       that it doesn't create the superfluous array variable @array.
138
139       If you write just "[]", you get a new, empty anonymous array.  If you
140       write just "{}", you get a new, empty anonymous hash.
141
142   Using References
143       What can you do with a reference once you have it?  It's a scalar
144       value, and we've seen that you can store it as a scalar and get it back
145       again just like any scalar.  There are just two more ways to use it:
146
147       Use Rule 1
148
149       You can always use an array reference, in curly braces, in place of the
150       name of an array.  For example, "@{$aref}" instead of @array.
151
152       Here are some examples of that:
153
154       Arrays:
155
156               @a              @{$aref}                An array
157               reverse @a      reverse @{$aref}        Reverse the array
158               $a[3]           ${$aref}[3]             An element of the array
159               $a[3] = 17;     ${$aref}[3] = 17        Assigning an element
160
161       On each line are two expressions that do the same thing.  The left-hand
162       versions operate on the array @a.  The right-hand versions operate on
163       the array that is referred to by $aref.  Once they find the array
164       they're operating on, both versions do the same things to the arrays.
165
166       Using a hash reference is exactly the same:
167
168               %h              %{$href}              A hash
169               keys %h         keys %{$href}         Get the keys from the hash
170               $h{'red'}       ${$href}{'red'}       An element of the hash
171               $h{'red'} = 17  ${$href}{'red'} = 17  Assigning an element
172
173       Whatever you want to do with a reference, Use Rule 1 tells you how to
174       do it.  You just write the Perl code that you would have written for
175       doing the same thing to a regular array or hash, and then replace the
176       array or hash name with "{$reference}".  "How do I loop over an array
177       when all I have is a reference?"  Well, to loop over an array, you
178       would write
179
180               for my $element (@array) {
181                 ...
182               }
183
184       so replace the array name, @array, with the reference:
185
186               for my $element (@{$aref}) {
187                 ...
188               }
189
190       "How do I print out the contents of a hash when all I have is a
191       reference?"  First write the code for printing out a hash:
192
193               for my $key (keys %hash) {
194                 print "$key => $hash{$key}\n";
195               }
196
197       And then replace the hash name with the reference:
198
199               for my $key (keys %{$href}) {
200                 print "$key => ${$href}{$key}\n";
201               }
202
203       Use Rule 2
204
205       Use Rule 1 is all you really need, because it tells you how to do
206       absolutely everything you ever need to do with references.  But the
207       most common thing to do with an array or a hash is to extract a single
208       element, and the Use Rule 1 notation is cumbersome.  So there is an
209       abbreviation.
210
211       "${$aref}[3]" is too hard to read, so you can write "$aref->[3]"
212       instead.
213
214       "${$href}{red}" is too hard to read, so you can write "$href->{red}"
215       instead.
216
217       If $aref holds a reference to an array, then "$aref->[3]" is the fourth
218       element of the array.  Don't confuse this with $aref[3], which is the
219       fourth element of a totally different array, one deceptively named
220       @aref.  $aref and @aref are unrelated the same way that $item and @item
221       are.
222
223       Similarly, "$href->{'red'}" is part of the hash referred to by the
224       scalar variable $href, perhaps even one with no name.  $href{'red'} is
225       part of the deceptively named %href hash.  It's easy to forget to leave
226       out the "->", and if you do, you'll get bizarre results when your
227       program gets array and hash elements out of totally unexpected hashes
228       and arrays that weren't the ones you wanted to use.
229
230   An Example
231       Let's see a quick example of how all this is useful.
232
233       First, remember that "[1, 2, 3]" makes an anonymous array containing
234       "(1, 2, 3)", and gives you a reference to that array.
235
236       Now think about
237
238               @a = ( [1, 2, 3],
239                      [4, 5, 6],
240                      [7, 8, 9]
241                    );
242
243       @a is an array with three elements, and each one is a reference to
244       another array.
245
246       $a[1] is one of these references.  It refers to an array, the array
247       containing "(4, 5, 6)", and because it is a reference to an array, Use
248       Rule 2 says that we can write "$a[1]->[2]" to get the third element
249       from that array.  "$a[1]->[2]" is the 6.  Similarly, "$a[0]->[1]" is
250       the 2.  What we have here is like a two-dimensional array; you can
251       write "$a[ROW]->[COLUMN]" to get or set the element in any row and any
252       column of the array.
253
254       The notation still looks a little cumbersome, so there's one more
255       abbreviation:
256
257   Arrow Rule
258       In between two subscripts, the arrow is optional.
259
260       Instead of "$a[1]->[2]", we can write "$a[1][2]"; it means the same
261       thing.  Instead of "$a[0]->[1] = 23", we can write "$a[0][1] = 23"; it
262       means the same thing.
263
264       Now it really looks like two-dimensional arrays!
265
266       You can see why the arrows are important.  Without them, we would have
267       had to write "${$a[1]}[2]" instead of "$a[1][2]".  For three-
268       dimensional arrays, they let us write "$x[2][3][5]" instead of the
269       unreadable "${${$x[2]}[3]}[5]".
270

Solution

272       Here's the answer to the problem I posed earlier, of reformatting a
273       file of city and country names.
274
275           1   my %table;
276
277           2   while (<>) {
278           3     chomp;
279           4     my ($city, $country) = split /, /;
280           5     $table{$country} = [] unless exists $table{$country};
281           6     push @{$table{$country}}, $city;
282           7   }
283
284           8   for my $country (sort keys %table) {
285           9     print "$country: ";
286          10     my @cities = @{$table{$country}};
287          11     print join ', ', sort @cities;
288          12     print ".\n";
289          13   }
290
291       The program has two pieces: Lines 2-7 read the input and build a data
292       structure, and lines 8-13 analyze the data and print out the report.
293       We're going to have a hash, %table, whose keys are country names, and
294       whose values are references to arrays of city names.  The data
295       structure will look like this:
296
297                  %table
298               +-------+---+
299               |       |   |   +-----------+--------+
300               |Germany| *---->| Frankfurt | Berlin |
301               |       |   |   +-----------+--------+
302               +-------+---+
303               |       |   |   +----------+
304               |Finland| *---->| Helsinki |
305               |       |   |   +----------+
306               +-------+---+
307               |       |   |   +---------+------------+----------+
308               |  USA  | *---->| Chicago | Washington | New York |
309               |       |   |   +---------+------------+----------+
310               +-------+---+
311
312       We'll look at output first.  Supposing we already have this structure,
313       how do we print it out?
314
315           8   for my $country (sort keys %table) {
316           9     print "$country: ";
317          10     my @cities = @{$table{$country}};
318          11     print join ', ', sort @cities;
319          12     print ".\n";
320          13   }
321
322       %table is an ordinary hash, and we get a list of keys from it, sort the
323       keys, and loop over the keys as usual.  The only use of references is
324       in line 10.  $table{$country} looks up the key $country in the hash and
325       gets the value, which is a reference to an array of cities in that
326       country.  Use Rule 1 says that we can recover the array by saying
327       "@{$table{$country}}".  Line 10 is just like
328
329               @cities = @array;
330
331       except that the name "array" has been replaced by the reference
332       "{$table{$country}}".  The "@" tells Perl to get the entire array.
333       Having gotten the list of cities, we sort it, join it, and print it out
334       as usual.
335
336       Lines 2-7 are responsible for building the structure in the first
337       place.  Here they are again:
338
339           2   while (<>) {
340           3     chomp;
341           4     my ($city, $country) = split /, /;
342           5     $table{$country} = [] unless exists $table{$country};
343           6     push @{$table{$country}}, $city;
344           7   }
345
346       Lines 2-4 acquire a city and country name.  Line 5 looks to see if the
347       country is already present as a key in the hash.  If it's not, the
348       program uses the "[]" notation (Make Rule 2) to manufacture a new,
349       empty anonymous array of cities, and installs a reference to it into
350       the hash under the appropriate key.
351
352       Line 6 installs the city name into the appropriate array.
353       $table{$country} now holds a reference to the array of cities seen in
354       that country so far.  Line 6 is exactly like
355
356               push @array, $city;
357
358       except that the name "array" has been replaced by the reference
359       "{$table{$country}}".  The "push" adds a city name to the end of the
360       referred-to array.
361
362       There's one fine point I skipped.  Line 5 is unnecessary, and we can
363       get rid of it.
364
365           2   while (<>) {
366           3     chomp;
367           4     my ($city, $country) = split /, /;
368           5   ####  $table{$country} = [] unless exists $table{$country};
369           6     push @{$table{$country}}, $city;
370           7   }
371
372       If there's already an entry in %table for the current $country, then
373       nothing is different.  Line 6 will locate the value in
374       $table{$country}, which is a reference to an array, and push $city into
375       the array.  But what does it do when $country holds a key, say
376       "Greece", that is not yet in %table?
377
378       This is Perl, so it does the exact right thing.  It sees that you want
379       to push "Athens" onto an array that doesn't exist, so it helpfully
380       makes a new, empty, anonymous array for you, installs it into %table,
381       and then pushes "Athens" onto it.  This is called
382       autovivification--bringing things to life automatically.  Perl saw that
383       the key wasn't in the hash, so it created a new hash entry
384       automatically. Perl saw that you wanted to use the hash value as an
385       array, so it created a new empty array and installed a reference to it
386       in the hash automatically.  And as usual, Perl made the array one
387       element longer to hold the new city name.
388

The Rest

390       I promised to give you 90% of the benefit with 10% of the details, and
391       that means I left out 90% of the details.  Now that you have an
392       overview of the important parts, it should be easier to read the
393       perlref manual page, which discusses 100% of the details.
394
395       Some of the highlights of perlref:
396
397       •   You can make references to anything, including scalars, functions,
398           and other references.
399
400       •   In Use Rule 1, you can omit the curly brackets whenever the thing
401           inside them is an atomic scalar variable like $aref.  For example,
402           @$aref is the same as "@{$aref}", and $$aref[1] is the same as
403           "${$aref}[1]".  If you're just starting out, you may want to adopt
404           the habit of always including the curly brackets.
405
406       •   This doesn't copy the underlying array:
407
408                   $aref2 = $aref1;
409
410           You get two references to the same array.  If you modify
411           "$aref1->[23]" and then look at "$aref2->[23]" you'll see the
412           change.
413
414           To copy the array, use
415
416                   $aref2 = [@{$aref1}];
417
418           This uses "[...]" notation to create a new anonymous array, and
419           $aref2 is assigned a reference to the new array.  The new array is
420           initialized with the contents of the array referred to by $aref1.
421
422           Similarly, to copy an anonymous hash, you can use
423
424                   $href2 = {%{$href1}};
425
426       •   To see if a variable contains a reference, use the "ref" function.
427           It returns true if its argument is a reference.  Actually it's a
428           little better than that: It returns "HASH" for hash references and
429           "ARRAY" for array references.
430
431       •   If you try to use a reference like a string, you get strings like
432
433                   ARRAY(0x80f5dec)   or    HASH(0x826afc0)
434
435           If you ever see a string that looks like this, you'll know you
436           printed out a reference by mistake.
437
438           A side effect of this representation is that you can use "eq" to
439           see if two references refer to the same thing.  (But you should
440           usually use "==" instead because it's much faster.)
441
442       •   You can use a string as if it were a reference.  If you use the
443           string "foo" as an array reference, it's taken to be a reference to
444           the array @foo.  This is called a symbolic reference.  The
445           declaration "use strict 'refs'" disables this feature, which can
446           cause all sorts of trouble if you use it by accident.
447
448       You might prefer to go on to perllol instead of perlref; it discusses
449       lists of lists and multidimensional arrays in detail.  After that, you
450       should move on to perldsc; it's a Data Structure Cookbook that shows
451       recipes for using and printing out arrays of hashes, hashes of arrays,
452       and other kinds of data.
453

Summary

455       Everyone needs compound data structures, and in Perl the way you get
456       them is with references.  There are four important rules for managing
457       references: Two for making references and two for using them.  Once you
458       know these rules you can do most of the important things you need to do
459       with references.
460

Credits

462       Author: Mark Jason Dominus, Plover Systems ("mjd-perl-ref+@plover.com")
463
464       This article originally appeared in The Perl Journal (
465       <http://www.tpj.com/> ) volume 3, #2.  Reprinted with permission.
466
467       The original title was Understand References Today.
468
469   Distribution Conditions
470       Copyright 1998 The Perl Journal.
471
472       This documentation is free; you can redistribute it and/or modify it
473       under the same terms as Perl itself.
474
475       Irrespective of its distribution, all code examples in these files are
476       hereby placed into the public domain.  You are permitted and encouraged
477       to use this code in your own programs for fun or for profit as you see
478       fit.  A simple comment in the code giving credit would be courteous but
479       is not required.
480
481
482
483perl v5.38.2                      2023-11-30                     PERLREFTUT(1)
Impressum