Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

416 lines
15 KiB

  1. =head1 NAME
  2. perlreftut - Mark's very short tutorial about references
  3. =head1 DESCRIPTION
  4. One of the most important new features in Perl 5 was the capability to
  5. manage complicated data structures like multidimensional arrays and
  6. nested hashes. To enable these, Perl 5 introduced a feature called
  7. `references', and using references is the key to managing complicated,
  8. structured data in Perl. Unfortunately, there's a lot of funny syntax
  9. to learn, and the main manual page can be hard to follow. The manual
  10. is quite complete, and sometimes people find that a problem, because
  11. it can be hard to tell what is important and what isn't.
  12. Fortunately, you only need to know 10% of what's in the main page to get
  13. 90% of the benefit. This page will show you that 10%.
  14. =head1 Who Needs Complicated Data Structures?
  15. One problem that came up all the time in Perl 4 was how to represent a
  16. hash whose values were lists. Perl 4 had hashes, of course, but the
  17. values had to be scalars; they couldn't be lists.
  18. Why would you want a hash of lists? Let's take a simple example: You
  19. have a file of city and country names, like this:
  20. Chicago, USA
  21. Frankfurt, Germany
  22. Berlin, Germany
  23. Washington, USA
  24. Helsinki, Finland
  25. New York, USA
  26. and you want to produce an output like this, with each country mentioned
  27. once, and then an alphabetical list of the cities in that country:
  28. Finland: Helsinki.
  29. Germany: Berlin, Frankfurt.
  30. USA: Chicago, New York, Washington.
  31. The natural way to do this is to have a hash whose keys are country
  32. names. Associated with each country name key is a list of the cities in
  33. that country. Each time you read a line of input, split it into a country
  34. and a city, look up the list of cities already known to be in that
  35. country, and append the new city to the list. When you're done reading
  36. the input, iterate over the hash as usual, sorting each list of cities
  37. before you print it out.
  38. If hash values can't be lists, you lose. In Perl 4, hash values can't
  39. be lists; they can only be strings. You lose. You'd probably have to
  40. combine all the cities into a single string somehow, and then when
  41. time came to write the output, you'd have to break the string into a
  42. list, sort the list, and turn it back into a string. This is messy
  43. and error-prone. And it's frustrating, because Perl already has
  44. perfectly good lists that would solve the problem if only you could
  45. use them.
  46. =head1 The Solution
  47. By the time Perl 5 rolled around, we were already stuck with this
  48. design: Hash values must be scalars. The solution to this is
  49. references.
  50. A reference is a scalar value that I<refers to> an entire array or an
  51. entire hash (or to just about anything else). Names are one kind of
  52. reference that you're already familiar with. Think of the President:
  53. a messy, inconvenient bag of blood and bones. But to talk about him,
  54. or to represent him in a computer program, all you need is the easy,
  55. convenient scalar string "Bill Clinton".
  56. References in Perl are like names for arrays and hashes. They're
  57. Perl's private, internal names, so you can be sure they're
  58. unambiguous. Unlike "Bill Clinton", a reference only refers to one
  59. thing, and you always know what it refers to. If you have a reference
  60. to an array, you can recover the entire array from it. If you have a
  61. reference to a hash, you can recover the entire hash. But the
  62. reference is still an easy, compact scalar value.
  63. You can't have a hash whose values are arrays; hash values can only be
  64. scalars. We're stuck with that. But a single reference can refer to
  65. an entire array, and references are scalars, so you can have a hash of
  66. references to arrays, and it'll act a lot like a hash of arrays, and
  67. it'll be just as useful as a hash of arrays.
  68. We'll come back to this city-country problem later, after we've seen
  69. some syntax for managing references.
  70. =head1 Syntax
  71. There are just two ways to make a reference, and just two ways to use
  72. it once you have it.
  73. =head2 Making References
  74. B<Make Rule 1>
  75. If you put a C<\> in front of a variable, you get a
  76. reference to that variable.
  77. $aref = \@array; # $aref now holds a reference to @array
  78. $href = \%hash; # $href now holds a reference to %hash
  79. Once the reference is stored in a variable like $aref or $href, you
  80. can copy it or store it just the same as any other scalar value:
  81. $xy = $aref; # $xy now holds a reference to @array
  82. $p[3] = $href; # $p[3] now holds a reference to %hash
  83. $z = $p[3]; # $z now holds a reference to %hash
  84. These examples show how to make references to variables with names.
  85. Sometimes you want to make an array or a hash that doesn't have a
  86. name. This is analogous to the way you like to be able to use the
  87. string C<"\n"> or the number 80 without having to store it in a named
  88. variable first.
  89. B<Make Rule 2>
  90. C<[ ITEMS ]> makes a new, anonymous array, and returns a reference to
  91. that array. C<{ ITEMS }> makes a new, anonymous hash. and returns a
  92. reference to that hash.
  93. $aref = [ 1, "foo", undef, 13 ];
  94. # $aref now holds a reference to an array
  95. $href = { APR => 4, AUG => 8 };
  96. # $href now holds a reference to a hash
  97. The references you get from rule 2 are the same kind of
  98. references that you get from rule 1:
  99. # This:
  100. $aref = [ 1, 2, 3 ];
  101. # Does the same as this:
  102. @array = (1, 2, 3);
  103. $aref = \@array;
  104. The first line is an abbreviation for the following two lines, except
  105. that it doesn't create the superfluous array variable C<@array>.
  106. =head2 Using References
  107. What can you do with a reference once you have it? It's a scalar
  108. value, and we've seen that you can store it as a scalar and get it back
  109. again just like any scalar. There are just two more ways to use it:
  110. B<Use Rule 1>
  111. If C<$aref> contains a reference to an array, then you
  112. can put C<{$aref}> anywhere you would normally put the name of an
  113. array. For example, C<@{$aref}> instead of C<@array>.
  114. Here are some examples of that:
  115. Arrays:
  116. @a @{$aref} An array
  117. reverse @a reverse @{$aref} Reverse the array
  118. $a[3] ${$aref}[3] An element of the array
  119. $a[3] = 17; ${$aref}[3] = 17 Assigning an element
  120. On each line are two expressions that do the same thing. The
  121. left-hand versions operate on the array C<@a>, and the right-hand
  122. versions operate on the array that is referred to by C<$aref>, but
  123. once they find the array they're operating on, they do the same things
  124. to the arrays.
  125. Using a hash reference is I<exactly> the same:
  126. %h %{$href} A hash
  127. keys %h keys %{$href} Get the keys from the hash
  128. $h{'red'} ${$href}{'red'} An element of the hash
  129. $h{'red'} = 17 ${$href}{'red'} = 17 Assigning an element
  130. B<Use Rule 2>
  131. C<${$aref}[3]> is too hard to read, so you can write C<< $aref->[3] >>
  132. instead.
  133. C<${$href}{red}> is too hard to read, so you can write
  134. C<< $href->{red} >> instead.
  135. Most often, when you have an array or a hash, you want to get or set a
  136. single element from it. C<${$aref}[3]> and C<${$href}{'red'}> have
  137. too much punctuation, and Perl lets you abbreviate.
  138. If C<$aref> holds a reference to an array, then C<< $aref->[3] >> is
  139. the fourth element of the array. Don't confuse this with C<$aref[3]>,
  140. which is the fourth element of a totally different array, one
  141. deceptively named C<@aref>. C<$aref> and C<@aref> are unrelated the
  142. same way that C<$item> and C<@item> are.
  143. Similarly, C<< $href->{'red'} >> is part of the hash referred to by
  144. the scalar variable C<$href>, perhaps even one with no name.
  145. C<$href{'red'}> is part of the deceptively named C<%href> hash. It's
  146. easy to forget to leave out the C<< -> >>, and if you do, you'll get
  147. bizarre results when your program gets array and hash elements out of
  148. totally unexpected hashes and arrays that weren't the ones you wanted
  149. to use.
  150. =head1 An Example
  151. Let's see a quick example of how all this is useful.
  152. First, remember that C<[1, 2, 3]> makes an anonymous array containing
  153. C<(1, 2, 3)>, and gives you a reference to that array.
  154. Now think about
  155. @a = ( [1, 2, 3],
  156. [4, 5, 6],
  157. [7, 8, 9]
  158. );
  159. @a is an array with three elements, and each one is a reference to
  160. another array.
  161. C<$a[1]> is one of these references. It refers to an array, the array
  162. containing C<(4, 5, 6)>, and because it is a reference to an array,
  163. B<USE RULE 2> says that we can write C<< $a[1]->[2] >> to get the
  164. third element from that array. C<< $a[1]->[2] >> is the 6.
  165. Similarly, C<< $a[0]->[1] >> is the 2. What we have here is like a
  166. two-dimensional array; you can write C<< $a[ROW]->[COLUMN] >> to get
  167. or set the element in any row and any column of the array.
  168. The notation still looks a little cumbersome, so there's one more
  169. abbreviation:
  170. =head1 Arrow Rule
  171. In between two B<subscripts>, the arrow is optional.
  172. Instead of C<< $a[1]->[2] >>, we can write C<$a[1][2]>; it means the
  173. same thing. Instead of C<< $a[0]->[1] >>, we can write C<$a[0][1]>;
  174. it means the same thing.
  175. Now it really looks like two-dimensional arrays!
  176. You can see why the arrows are important. Without them, we would have
  177. had to write C<${$a[1]}[2]> instead of C<$a[1][2]>. For
  178. three-dimensional arrays, they let us write C<$x[2][3][5]> instead of
  179. the unreadable C<${${$x[2]}[3]}[5]>.
  180. =head1 Solution
  181. Here's the answer to the problem I posed earlier, of reformatting a
  182. file of city and country names.
  183. 1 while (<>) {
  184. 2 chomp;
  185. 3 my ($city, $country) = split /, /;
  186. 4 push @{$table{$country}}, $city;
  187. 5 }
  188. 6
  189. 7 foreach $country (sort keys %table) {
  190. 8 print "$country: ";
  191. 9 my @cities = @{$table{$country}};
  192. 10 print join ', ', sort @cities;
  193. 11 print ".\n";
  194. 12 }
  195. The program has two pieces: Lines 1--5 read the input and build a
  196. data structure, and lines 7--12 analyze the data and print out the
  197. report.
  198. In the first part, line 4 is the important one. We're going to have a
  199. hash, C<%table>, whose keys are country names, and whose values are
  200. (references to) arrays of city names. After acquiring a city and
  201. country name, the program looks up C<$table{$country}>, which holds (a
  202. reference to) the list of cities seen in that country so far. Line 4 is
  203. totally analogous to
  204. push @array, $city;
  205. except that the name C<array> has been replaced by the reference
  206. C<{$table{$country}}>. The C<push> adds a city name to the end of the
  207. referred-to array.
  208. In the second part, line 9 is the important one. Again,
  209. C<$table{$country}> is (a reference to) the list of cities in the country, so
  210. we can recover the original list, and copy it into the array C<@cities>,
  211. by using C<@{$table{$country}}>. Line 9 is totally analogous to
  212. @cities = @array;
  213. except that the name C<array> has been replaced by the reference
  214. C<{$table{$country}}>. The C<@> tells Perl to get the entire array.
  215. The rest of the program is just familiar uses of C<chomp>, C<split>, C<sort>,
  216. C<print>, and doesn't involve references at all.
  217. There's one fine point I skipped. Suppose the program has just read
  218. the first line in its input that happens to mention Greece.
  219. Control is at line 4, C<$country> is C<'Greece'>, and C<$city> is
  220. C<'Athens'>. Since this is the first city in Greece,
  221. C<$table{$country}> is undefined---in fact there isn't an C<'Greece'> key
  222. in C<%table> at all. What does line 4 do here?
  223. 4 push @{$table{$country}}, $city;
  224. This is Perl, so it does the exact right thing. It sees that you want
  225. to push C<Athens> onto an array that doesn't exist, so it helpfully
  226. makes a new, empty, anonymous array for you, installs it in the table,
  227. and then pushes C<Athens> onto it. This is called `autovivification'.
  228. =head1 The Rest
  229. I promised to give you 90% of the benefit with 10% of the details, and
  230. that means I left out 90% of the details. Now that you have an
  231. overview of the important parts, it should be easier to read the
  232. L<perlref> manual page, which discusses 100% of the details.
  233. Some of the highlights of L<perlref>:
  234. =over 4
  235. =item *
  236. You can make references to anything, including scalars, functions, and
  237. other references.
  238. =item *
  239. In B<USE RULE 1>, you can omit the curly brackets whenever the thing
  240. inside them is an atomic scalar variable like C<$aref>. For example,
  241. C<@$aref> is the same as C<@{$aref}>, and C<$$aref[1]> is the same as
  242. C<${$aref}[1]>. If you're just starting out, you may want to adopt
  243. the habit of always including the curly brackets.
  244. =item *
  245. To see if a variable contains a reference, use the `ref' function.
  246. It returns true if its argument is a reference. Actually it's a
  247. little better than that: It returns HASH for hash references and
  248. ARRAY for array references.
  249. =item *
  250. If you try to use a reference like a string, you get strings like
  251. ARRAY(0x80f5dec) or HASH(0x826afc0)
  252. If you ever see a string that looks like this, you'll know you
  253. printed out a reference by mistake.
  254. A side effect of this representation is that you can use C<eq> to see
  255. if two references refer to the same thing. (But you should usually use
  256. C<==> instead because it's much faster.)
  257. =item *
  258. You can use a string as if it were a reference. If you use the string
  259. C<"foo"> as an array reference, it's taken to be a reference to the
  260. array C<@foo>. This is called a I<soft reference> or I<symbolic reference>.
  261. =back
  262. You might prefer to go on to L<perllol> instead of L<perlref>; it
  263. discusses lists of lists and multidimensional arrays in detail. After
  264. that, you should move on to L<perldsc>; it's a Data Structure Cookbook
  265. that shows recipes for using and printing out arrays of hashes, hashes
  266. of arrays, and other kinds of data.
  267. =head1 Summary
  268. Everyone needs compound data structures, and in Perl the way you get
  269. them is with references. There are four important rules for managing
  270. references: Two for making references and two for using them. Once
  271. you know these rules you can do most of the important things you need
  272. to do with references.
  273. =head1 Credits
  274. Author: Mark-Jason Dominus, Plover Systems (C<[email protected]>)
  275. This article originally appeared in I<The Perl Journal>
  276. (http://tpj.com) volume 3, #2. Reprinted with permission.
  277. The original title was I<Understand References Today>.
  278. =head2 Distribution Conditions
  279. Copyright 1998 The Perl Journal.
  280. When included as part of the Standard Version of Perl, or as part of
  281. its complete documentation whether printed or otherwise, this work may
  282. be distributed only under the terms of Perl's Artistic License. Any
  283. distribution of this file or derivatives thereof outside of that
  284. package require that special arrangements be made with copyright
  285. holder.
  286. Irrespective of its distribution, all code examples in these files are
  287. hereby placed into the public domain. You are permitted and
  288. encouraged to use this code in your own programs for fun or for profit
  289. as you see fit. A simple comment in the code giving credit would be
  290. courteous but is not required.
  291. =cut