.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man 5.01 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .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 .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "PERLREFTUT 1" .TH PERLREFTUT 1 2023-11-28 "perl v5.38.2" "Perl Programmers Reference Guide" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .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 \&\fIreferences\fR, 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 comes up all the time is needing a hash whose values are lists. Perl has hashes, of course, but the values have to be scalars; they can'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 couldn't be lists, 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. Each human being is a messy, inconvenient collection of cells. But to refer to a particular human, for instance the first computer programmer, it isn't necessary to describe each of their cells; all you need is the easy, convenient scalar string "Ada Lovelace". .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 a human name, 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. .SS "Making References" .IX Subsection "Making References" \fR\f(BIMake Rule 1\fR\fI\fR .IX Subsection "Make Rule 1" .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 \fR\f(BIMake Rule 2\fR\fI\fR .IX Subsection "Make Rule 2" .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 \& \& $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 ]; \& \& # 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. .PP If you write just \f(CW\*(C`[]\*(C'\fR, you get a new, empty anonymous array. If you write just \f(CW\*(C`{}\*(C'\fR, you get a new, empty anonymous hash. .SS "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 \fR\f(BIUse Rule 1\fR\fI\fR .IX Subsection "Use Rule 1" .PP You can always use an array reference, in curly braces, in place of 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. The right-hand versions operate on the array that is referred to by \f(CW$aref\fR. Once they find the array they're operating on, both versions 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{\*(Aqred\*(Aq} ${$href}{\*(Aqred\*(Aq} An element of the hash \& $h{\*(Aqred\*(Aq} = 17 ${$href}{\*(Aqred\*(Aq} = 17 Assigning an element .Ve .PP Whatever you want to do with a reference, \fBUse Rule 1\fR tells you how to do it. You just write the Perl code that you would have written for doing the same thing to a regular array or hash, and then replace the array or hash name with \f(CW\*(C`{$reference}\*(C'\fR. "How do I loop over an array when all I have is a reference?" Well, to loop over an array, you would write .PP .Vb 3 \& for my $element (@array) { \& ... \& } .Ve .PP so replace the array name, \f(CW@array\fR, with the reference: .PP .Vb 3 \& for my $element (@{$aref}) { \& ... \& } .Ve .PP "How do I print out the contents of a hash when all I have is a reference?" First write the code for printing out a hash: .PP .Vb 3 \& for my $key (keys %hash) { \& print "$key => $hash{$key}\en"; \& } .Ve .PP And then replace the hash name with the reference: .PP .Vb 3 \& for my $key (keys %{$href}) { \& print "$key => ${$href}{$key}\en"; \& } .Ve .PP \fR\f(BIUse Rule 2\fR\fI\fR .IX Subsection "Use Rule 2" .PP \&\fBUse Rule 1\fR is all you really need, because it tells you how to do absolutely everything you ever need to do with references. But the most common thing to do with an array or a hash is to extract a single element, and the \fBUse Rule 1\fR notation is cumbersome. So there is an abbreviation. .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 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\->{\*(Aqred\*(Aq}\*(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{\*(Aqred\*(Aq}\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. .SS "An Example" .IX Subsection "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 \&\f(CW@a\fR 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, \&\fBUse Rule 2\fR says that we can write \f(CW\*(C`$a[1]\->[2]\*(C'\fR to get the third element from that array. \f(CW\*(C`$a[1]\->[2]\*(C'\fR is the 6. Similarly, \f(CW\*(C`$a[0]\->[1]\*(C'\fR is the 2. What we have here is like a two-dimensional array; you can write \f(CW\*(C`$a[ROW]\->[COLUMN]\*(C'\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: .SS "Arrow Rule" .IX Subsection "Arrow Rule" In between two \fBsubscripts\fR, the arrow is optional. .PP Instead of \f(CW\*(C`$a[1]\->[2]\*(C'\fR, we can write \f(CW\*(C`$a[1][2]\*(C'\fR; it means the same thing. Instead of \f(CW\*(C`$a[0]\->[1] = 23\*(C'\fR, we can write \&\f(CW\*(C`$a[0][1] = 23\*(C'\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\*(C`$a[1][2]\*(C'\fR. For three-dimensional arrays, they let us write \f(CW\*(C`$x[2][3][5]\*(C'\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 1 \& 1 my %table; \& \& 2 while (<>) { \& 3 chomp; \& 4 my ($city, $country) = split /, /; \& 5 $table{$country} = [] unless exists $table{$country}; \& 6 push @{$table{$country}}, $city; \& 7 } \& \& 8 for my $country (sort keys %table) { \& 9 print "$country: "; \& 10 my @cities = @{$table{$country}}; \& 11 print join \*(Aq, \*(Aq, sort @cities; \& 12 print ".\en"; \& 13 } .Ve .PP The program has two pieces: Lines 2\-7 read the input and build a data structure, and lines 8\-13 analyze the data and print out the report. 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. The data structure will look like this: .PP .Vb 10 \& %table \& +\-\-\-\-\-\-\-+\-\-\-+ \& | | | +\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-+ \& |Germany| *\-\-\-\->| Frankfurt | Berlin | \& | | | +\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-+ \& +\-\-\-\-\-\-\-+\-\-\-+ \& | | | +\-\-\-\-\-\-\-\-\-\-+ \& |Finland| *\-\-\-\->| Helsinki | \& | | | +\-\-\-\-\-\-\-\-\-\-+ \& +\-\-\-\-\-\-\-+\-\-\-+ \& | | | +\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-+ \& | USA | *\-\-\-\->| Chicago | Washington | New York | \& | | | +\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-+ \& +\-\-\-\-\-\-\-+\-\-\-+ .Ve .PP We'll look at output first. Supposing we already have this structure, how do we print it out? .PP .Vb 6 \& 8 for my $country (sort keys %table) { \& 9 print "$country: "; \& 10 my @cities = @{$table{$country}}; \& 11 print join \*(Aq, \*(Aq, sort @cities; \& 12 print ".\en"; \& 13 } .Ve .PP \&\f(CW%table\fR is an ordinary hash, and we get a list of keys from it, sort the keys, and loop over the keys as usual. The only use of references is in line 10. \f(CW$table{$country}\fR looks up the key \f(CW$country\fR in the hash and gets the value, which is a reference to an array of cities in that country. \fBUse Rule 1\fR says that we can recover the array by saying \f(CW\*(C`@{$table{$country}}\*(C'\fR. Line 10 is just like .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. Having gotten the list of cities, we sort it, join it, and print it out as usual. .PP Lines 2\-7 are responsible for building the structure in the first place. Here they are again: .PP .Vb 6 \& 2 while (<>) { \& 3 chomp; \& 4 my ($city, $country) = split /, /; \& 5 $table{$country} = [] unless exists $table{$country}; \& 6 push @{$table{$country}}, $city; \& 7 } .Ve .PP Lines 2\-4 acquire a city and country name. Line 5 looks to see if the country is already present as a key in the hash. If it's not, the program uses the \f(CW\*(C`[]\*(C'\fR notation (\fBMake Rule 2\fR) to manufacture a new, empty anonymous array of cities, and installs a reference to it into the hash under the appropriate key. .PP Line 6 installs the city name into the appropriate array. \&\f(CW$table{$country}\fR now holds a reference to the array of cities seen in that country so far. Line 6 is exactly like .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 There's one fine point I skipped. Line 5 is unnecessary, and we can get rid of it. .PP .Vb 6 \& 2 while (<>) { \& 3 chomp; \& 4 my ($city, $country) = split /, /; \& 5 #### $table{$country} = [] unless exists $table{$country}; \& 6 push @{$table{$country}}, $city; \& 7 } .Ve .PP If there's already an entry in \f(CW%table\fR for the current \f(CW$country\fR, then nothing is different. Line 6 will locate the value in \&\f(CW$table{$country}\fR, which is a reference to an array, and push \f(CW$city\fR into the array. But what does it do when \f(CW$country\fR holds a key, say \&\f(CW\*(C`Greece\*(C'\fR, that is not yet in \f(CW%table\fR? .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 into \&\f(CW%table\fR, and then pushes \f(CW\*(C`Athens\*(C'\fR onto it. This is called \&\fIautovivification\fR\-\-bringing things to life automatically. Perl saw that the key wasn't in the hash, so it created a new hash entry automatically. Perl saw that you wanted to use the hash value as an array, so it created a new empty array and installed a reference to it in the hash automatically. And as usual, Perl made the array one element longer to hold the new city name. .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 \fBUse Rule 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 This doesn't copy the underlying array: .Sp .Vb 1 \& $aref2 = $aref1; .Ve .Sp You get two references to the same array. If you modify \&\f(CW\*(C`$aref1\->[23]\*(C'\fR and then look at \&\f(CW\*(C`$aref2\->[23]\*(C'\fR you'll see the change. .Sp To copy the array, use .Sp .Vb 1 \& $aref2 = [@{$aref1}]; .Ve .Sp This uses \f(CW\*(C`[...]\*(C'\fR notation to create a new anonymous array, and \&\f(CW$aref2\fR is assigned a reference to the new array. The new array is initialized with the contents of the array referred to by \f(CW$aref1\fR. .Sp Similarly, to copy an anonymous hash, you can use .Sp .Vb 1 \& $href2 = {%{$href1}}; .Ve .IP \(bu 4 To see if a variable contains a reference, use the \&\f(CW\*(C`ref\*(C'\fR function. It returns true if its argument is a reference. Actually it's a little better than that: It returns \&\f(CW\*(C`HASH\*(C'\fR for hash references and \f(CW\*(C`ARRAY\*(C'\fR 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 \fIsymbolic reference\fR. The declaration \&\f(CW\*(C`use strict \*(Aqrefs\*(Aq\*(C'\fR disables this feature, which can cause all sorts of trouble if you use it by accident. .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 ( ) volume 3, #2. Reprinted with permission. .PP The original title was \fIUnderstand References Today\fR. .SS "Distribution Conditions" .IX Subsection "Distribution Conditions" Copyright 1998 The Perl Journal. .PP This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. .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.