home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / C / Applications / MacPerl 5.0.3 / MacPerl Source ƒ / MacPerl5 / pod / perlref.pod < prev    next >
Encoding:
Text File  |  1994-12-26  |  12.6 KB  |  230 lines  |  [TEXT/MPS ]

  1. =head1 NAME
  2.  
  3. perlref - Perl references and nested data structures
  4.  
  5. =head1 DESCRIPTION
  6.  
  7. In Perl 4 it was difficult to represent complex data structures, because
  8. all references had to be symbolic, and even that was difficult to do when
  9. you wanted to refer to a variable rather than a symbol table entry.  Perl
  10. 5 not only makes it easier to use symbolic references to variables, but
  11. lets you have "hard" references to any piece of data.  Any scalar may hold
  12. a hard reference.  Since arrays and hashes contain scalars, you can now
  13. easily build arrays of arrays, arrays of hashes, hashes of arrays, arrays
  14. 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.  
  53. =item 2.
  54.  
  55. A reference to an anonymous array can be constructed using square
  56. brackets:
  57.  
  58.     $arrayref = [1, 2, ['a', 'b', 'c']];
  59.  
  60. Here we've constructed a reference to an anonymous array of three elements
  61. whose final element is itself reference to another anonymous array of three
  62. elements.  (The multidimensional syntax described later can be used to
  63. access this.  For example, after the above, $arrayref->[2][1] would have
  64. the value "b".)
  65.  
  66. =item 3.
  67.  
  68. A reference to an anonymous hash can be constructed using curly
  69. brackets:
  70.  
  71.     $hashref = {
  72.     'Adam'  => 'Eve',
  73.     'Clyde' => 'Bonnie',
  74.     };
  75.  
  76. Anonymous hash and array constructors can be intermixed freely to
  77. produce as complicated a structure as you want.  The multidimensional
  78. syntax described below works for these too.  The vier with a BLOCK returning a reference
  79. of the correct type.  In other words, the previous examples could be
  80. written like this:
  81.  
  82.     $bar = ${$scalarref};
  83.     push(@{$arrayref}, $filename);
  84.     ${$arrayref}[0] = "January";
  85.     ${$hashref}{"KEY"} = "VALUE";
  86.     &{$coderef}(1,2,3);
  87.  
  88. Admittedly, it's a little silly to use the curlies in this case, but
  89. the BLOCK can contain any arbitrary expression, in particular,
  90. subscripted expressions:
  91.  
  92.     &{ $dispatch{$index} }(1,2,3);    # call correct routine 
  93.  
  94. Because of being able to omit the curlies for the simple case of C<$$x>,
  95. people often make the mistake of viewing the dereferencing symbols as
  96. proper operators, and wonder about their precedence.  If they were,
  97. though, you could use parens instead of braces.  That's not the case.
  98. Consider the difference below; case 0 is a short-hand version of case 1,
  99. I<NOT> case 2:
  100.  
  101.     $$hashref{"KEY"}   = "VALUE";    # CASE 0
  102.     ${$hashref}{"KEY"} = "VALUE";    # CASE 1
  103.     ${$hashref{"KEY"}} = "VALUE";    # CASE 2
  104.     ${$hashref->{"KEY"}} = "VALUE";    # CASE 3
  105.  
  106. Case 2 is also deceptive in that you're accessing a variable
  107. called %hashref, not dereferencing through $hashref to the hash
  108. it's presumably referencing.  That would be case 3.
  109.  
  110. =item 3.
  111.  
  112. The case of individual array elements arises often enough that it gets
  113. cumbersome to use method 2.  As a form of syntactic sugar, the two
  114. lines like that above can be written:
  115.  
  116.     $arrayref->[0] = "January";
  117.     $hashref->{"KEY} = "VALUE";
  118.  
  119. The left side of the array can be any expression returning a reference,
  120. including a previous dereference.  Note that C<$array[$x]> is I<NOT> the
  121. same thing as C<$array-E<gt>[$x]> here:
  122.  
  123.     $array[$x]->{"foo"}->[0] = "January";
  124.  
  125. This is one of the cases we mentioned earlier in which references could
  126. spring into existence when in an lvalue context.  Before this
  127. statement, C<$array[$x]> may have been undefined.  If so, it's
  128. automatically defined with a hash reference so that we can look up
  129. C<{"foo"}> in it.  Likewise C<$array[$x]-E<gt>{"foo"}> will automatically get
  130. defined with an array reference so that we can look up C<[0]> in it.
  131.  
  132. One more thing here.  The arrow is optional I<BETWEEN> brackets
  133. subscripts, so you can shrink the above down to
  134.  
  135.     $array[$x]{"foo"}[0] = "January";
  136.  
  137. Which, in the degenerate case of using only ordinary arrays, gives you
  138. multidimensional arrays just like C's:
  139.  
  140.     $score[$x][$y][$z] += 42;
  141.  
  142. Well, okay, not entirely like C's arrays, actually.  C doesn't know how
  143. to grow its arrays on demand.  Perl does.
  144.  
  145. =item 4.
  146.  
  147. If a reference happens to be a reference to an object, then there are
  148. probably methods to access the things referred to, and you should probably
  149. stick to those methods unless you're in the class package that defines the
  150. object's methods.  In other words, be nice, and don't violate the object's
  151. encapsulation without a very good reason.  Perl does not enforce
  152. encapsulation.  We are not totalitarians here.  We do expect some basic
  153. civility though.
  154.  
  155. =back
  156.  
  157. The ref() operator may be used to determine what type of thing the
  158. reference is pointing to.  See L<perlfunc>.
  159.  
  160. The bless() operator may be used to associate a reference with a package
  161. functioning as an object class.  See L<perlobj>.
  162.  
  163. A type glob may be dereferenced the same way a reference can, since
  164. the dereference syntax always indicates the kind of reference desired.
  165. So C<${*foo}> and C<${\$foo}> both indicate the same scalar variable.
  166.  
  167. Here's a trick for interpolating a subroutine call into a string:
  168.  
  169.     print "My sub returned ${\mysub(1,2,3)}\n";
  170.  
  171. The way it works is that when the C<${...}> is seen in the double-quoted
  172. string, it's evaluated as a block.  The block executes the call to
  173. C<mysub(1,2,3)>, and then takes a reference to that.  So the whole block
  174. returns a reference to a scalar, which is then dereferenced by C<${...}>
  175. and stuck into the double-quoted string.
  176.  
  177. =head2 Symbolic references
  178.  
  179. We said that references spring into existence as necessary if they are
  180. undefined, but we didn't say what happens if a value used as a
  181. reference is already defined, but I<ISN'T> a hard reference.  If you
  182. use it as a reference in this case, it'll be treated as a symbolic
  183. reference.  That is, the value of the scalar is taken to be the I<NAME>
  184. of a variable, rather than a direct link to a (possibly) anonymous
  185. value.
  186.  
  187. People frequently expect it to work like this.  So it does.
  188.  
  189.     $name = "foo";
  190.     $$name = 1;            # Sets $foo
  191.     ${$name} = 2;        # Sets $foo
  192.     ${$name x 2} = 3;        # Sets $foofoo
  193.     $name->[0] = 4;        # Sets $foo[0]
  194.     @$name = ();        # Clears @foo
  195.     &$name();            # Calls &foo() (as in Perl 4)
  196.     $pack = "THAT";
  197.     ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
  198.  
  199. This is very powerful, and slightly dangerous, in that it's possible
  200. to intend (with the utmost sincerity) to use a hard reference, and
  201. accidentally use a symbolic reference instead.  To protect against
  202. that, you can say
  203.  
  204.     use strict 'refs';
  205.  
  206. and then only hard references will be allowed for the rest of the enclosing
  207. block.  An inner block may countermand that with 
  208.  
  209.     no strict 'refs';
  210.  
  211. Only package variables are visible to symbolic references.  Lexical
  212. variables (declared with my()) aren't in a symbol table, and thus are
  213. invisible to this mechanism.  For example:
  214.  
  215.     local($value) = 10;
  216.     $ref = \$value;
  217.     {
  218.     my $value = 20;
  219.     print $$ref;
  220.     } 
  221.  
  222. This will still print 10, not 20.  Remember that local() affects package
  223. variables, which are all "global" to the package.
  224.  
  225. =head2 Further Reading
  226.  
  227. Besides the obvious documents, source code can be instructive.
  228. Some rather pathological examples of the use of references can be found
  229. in the F<t/op/ref.t> regression test in the Perl source directory.
  230.