home *** CD-ROM | disk | FTP | other *** search
/ BURKS 2 / BURKS_AUG97.ISO / SLAKWARE / D13 / PERL2.TGZ / perl2.tar / usr / lib / perl5 / pod / perlref.pod < prev    next >
Text File  |  1996-06-28  |  17KB  |  465 lines

  1. =head1 NAME
  2.  
  3. perlref - Perl references and nested data structures
  4.  
  5. =head1 DESCRIPTION
  6.  
  7. Before release 5 of Perl it was difficult to represent complex data
  8. structures, because all references had to be symbolic, and even that was
  9. difficult to do when you wanted to refer to a variable rather than a
  10. symbol table entry.  Perl 5 not only makes it easier to use symbolic
  11. references to variables, but lets you have "hard" references to any piece
  12. of data.  Any scalar may hold a hard reference.  Since arrays and hashes
  13. contain scalars, you can now easily build arrays of arrays, arrays of
  14. hashes, hashes of arrays, arrays of hashes of functions, and so on.
  15.  
  16. Hard references are smart--they keep track of reference counts for you,
  17. automatically freeing the thing referred to when its reference count
  18. goes to zero.  If that thing happens to be an object, the object is
  19. destructed.  See L<perlobj> for more about objects.  (In a sense,
  20. everything in Perl is an object, but we usually reserve the word for
  21. references to objects that have been officially "blessed" into a class package.)
  22.  
  23. A symbolic reference contains the name of a variable, just as a
  24. symbolic link in the filesystem merely contains the name of a file.  
  25. The C<*glob> notation is a kind of symbolic reference.  Hard references
  26. are more like hard links in the file system: merely another way
  27. at getting at the same underlying object, irrespective of its name.
  28.  
  29. "Hard" references are easy to use in Perl.  There is just one
  30. overriding principle:  Perl does no implicit referencing or
  31. dereferencing.  When a scalar is holding a reference, it always behaves
  32. as a scalar.  It doesn't magically start being an array or a hash
  33. unless you tell it so explicitly by dereferencing it.
  34.  
  35. References can be constructed several ways.
  36.  
  37. =over 4
  38.  
  39. =item 1.
  40.  
  41. By using the backslash operator on a variable, subroutine, or value.
  42. (This works much like the & (address-of) operator works in C.)  Note
  43. that this typically creates I<ANOTHER> reference to a variable, since
  44. there's already a reference to the variable in the symbol table.  But
  45. the symbol table reference might go away, and you'll still have the
  46. reference that the backslash returned.  Here are some examples:
  47.  
  48.     $scalarref = \$foo;
  49.     $arrayref  = \@ARGV;
  50.     $hashref   = \%ENV;
  51.     $coderef   = \&handler;
  52.     $globref   = \*STDOUT;
  53.  
  54.  
  55. =item 2.
  56.  
  57. A reference to an anonymous array can be constructed using square
  58. brackets:
  59.  
  60.     $arrayref = [1, 2, ['a', 'b', 'c']];
  61.  
  62. Here we've constructed a reference to an anonymous array of three elements
  63. whose final element is itself reference to another anonymous array of three
  64. elements.  (The multidimensional syntax described later can be used to
  65. access this.  For example, after the above, $arrayref-E<gt>[2][1] would have
  66. the value "b".)
  67.  
  68. Note that taking a reference to an enumerated list is not the same
  69. as using square brackets--instead it's the same as creating
  70. a list of references!
  71.  
  72.     @list = (\$a, \$b, \$c);  
  73.     @list = \($a, $b, $c);    # same thing!
  74.  
  75. =item 3.
  76.  
  77. A reference to an anonymous hash can be constructed using curly
  78. brackets:
  79.  
  80.     $hashref = {
  81.     'Adam'  => 'Eve',
  82.     'Clyde' => 'Bonnie',
  83.     };
  84.  
  85. Anonymous hash and array constructors can be intermixed freely to
  86. produce as complicated a structure as you want.  The multidimensional
  87. syntax described below works for these too.  The values above are
  88. literals, but variables and expressions would work just as well, because
  89. assignment operators in Perl (even within local() or my()) are executable
  90. statements, not compile-time declarations.
  91.  
  92. Because curly brackets (braces) are used for several other things
  93. including BLOCKs, you may occasionally have to disambiguate braces at the
  94. beginning of a statement by putting a C<+> or a C<return> in front so
  95. that Perl realizes the opening brace isn't starting a BLOCK.  The economy and
  96. mnemonic value of using curlies is deemed worth this occasional extra
  97. hassle.
  98.  
  99. For example, if you wanted a function to make a new hash and return a
  100. reference to it, you have these options:
  101.  
  102.     sub hashem {        { @_ } }   # silently wrong
  103.     sub hashem {       +{ @_ } }   # ok
  104.     sub hashem { return { @_ } }   # ok
  105.  
  106. =item 4.
  107.  
  108. A reference to an anonymous subroutine can be constructed by using
  109. C<sub> without a subname:
  110.  
  111.     $coderef = sub { print "Boink!\n" };
  112.  
  113. Note the presence of the semicolon.  Except for the fact that the code
  114. inside isn't executed immediately, a C<sub {}> is not so much a
  115. declaration as it is an operator, like C<do{}> or C<eval{}>.  (However, no
  116. matter how many times you execute that line (unless you're in an
  117. C<eval("...")>), C<$coderef> will still have a reference to the I<SAME>
  118. anonymous subroutine.)
  119.  
  120. Anonymous subroutines act as closures with respect to my() variables,
  121. that is, variables visible lexically within the current scope.  Closure
  122. is a notion out of the Lisp world that says if you define an anonymous
  123. function in a particular lexical context, it pretends to run in that
  124. context even when it's called outside of the context.
  125.  
  126. In human terms, it's a funny way of passing arguments to a subroutine when
  127. you define it as well as when you call it.  It's useful for setting up
  128. little bits of code to run later, such as callbacks.  You can even
  129. do object-oriented stuff with it, though Perl provides a different
  130. mechanism to do that already--see L<perlobj>.
  131.  
  132. You can also think of closure as a way to write a subroutine template without
  133. using eval.  (In fact, in version 5.000, eval was the I<only> way to get
  134. closures.  You may wish to use "require 5.001" if you use closures.)
  135.  
  136. Here's a small example of how closures works:
  137.  
  138.     sub newprint {
  139.     my $x = shift;
  140.     return sub { my $y = shift; print "$x, $y!\n"; };
  141.     }
  142.     $h = newprint("Howdy");
  143.     $g = newprint("Greetings");
  144.  
  145.     # Time passes...
  146.  
  147.     &$h("world");
  148.     &$g("earthlings");
  149.  
  150. This prints
  151.  
  152.     Howdy, world!
  153.     Greetings, earthlings!
  154.  
  155. Note particularly that $x continues to refer to the value passed into
  156. newprint() I<despite> the fact that the "my $x" has seemingly gone out of
  157. scope by the time the anonymous subroutine runs.  That's what closure
  158. is all about.
  159.  
  160. This only applies to lexical variables, by the way.  Dynamic variables
  161. continue to work as they have always worked.  Closure is not something
  162. that most Perl programmers need trouble themselves about to begin with.
  163.  
  164. =item 5.
  165.  
  166. References are often returned by special subroutines called constructors.
  167. Perl objects are just references to a special kind of object that happens to know
  168. which package it's associated with.  Constructors are just special
  169. subroutines that know how to create that association.  They do so by
  170. starting with an ordinary reference, and it remains an ordinary reference
  171. even while it's also being an object.  Constructors are customarily
  172. named new(), but don't have to be:
  173.  
  174.     $objref = new Doggie (Tail => 'short', Ears => 'long');
  175.  
  176. =item 6.
  177.  
  178. References of the appropriate type can spring into existence if you
  179. dereference them in a context that assumes they exist.  Since we haven't
  180. talked about dereferencing yet, we can't show you any examples yet.
  181.  
  182. =item 7.
  183.  
  184. References to filehandles can be created by taking a reference to 
  185. a typeglob.  This is currently the best way to pass filehandles into or
  186. out of subroutines, or to store them in larger data structures.
  187.  
  188.     splutter(\*STDOUT);
  189.     sub splutter {
  190.     my $fh = shift;
  191.     print $fh "her um well a hmmm\n";
  192.     }
  193.  
  194.     $rec = get_rec(\*STDIN);
  195.     sub get_rec {
  196.     my $fh = shift;
  197.     return scalar <$fh>;
  198.     }
  199.  
  200. =back
  201.  
  202. That's it for creating references.  By now you're probably dying to
  203. know how to use references to get back to your long-lost data.  There
  204. are several basic methods.
  205.  
  206. =over 4
  207.  
  208. =item 1.
  209.  
  210. Anywhere you'd put an identifier as part of a variable or subroutine
  211. name, you can replace the identifier with a simple scalar variable
  212. containing a reference of the correct type:
  213.  
  214.     $bar = $$scalarref;
  215.     push(@$arrayref, $filename);
  216.     $$arrayref[0] = "January";
  217.     $$hashref{"KEY"} = "VALUE";
  218.     &$coderef(1,2,3);
  219.     print $globref "output\n";
  220.  
  221. It's important to understand that we are specifically I<NOT> dereferencing
  222. C<$arrayref[0]> or C<$hashref{"KEY"}> there.  The dereference of the
  223. s