home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / perl5000.zip / perl5000 / pod / perlref.pod < prev    next >
Encoding:
Text File  |  1994-10-17  |  12.6 KB  |  333 lines

  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 values above are
  79. literals, but variables and expressions would work just as well, because
  80. assignment operators in Perl (even within local() or my()) are executable
  81. statements, not compile-time declarations.
  82.  
  83. Because curly brackets (braces) are used for several other things
  84. including BLOCKs, you may occasionally have to disambiguate braces at the
  85. beginning of a statement by putting a C<+> or a C<return> in front so
  86. that Perl realizes the opening brace isn't starting a BLOCK.  The economy and
  87. mnemonic value of using curlies is deemed worth this occasional extra
  88. hassle.
  89.  
  90. For example, if you wanted a function to make a new hash and return a
  91. reference to it, you have these options:
  92.  
  93.     sub hashem {        { @_ } }   # silently wrong
  94.     sub hashem {       +{ @_ } }   # ok
  95.     sub hashem { return { @_ } }   # ok
  96.  
  97. =item 4.
  98.  
  99. A reference to an anonymous subroutine can be constructed by using
  100. C<sub> without a subname:
  101.  
  102.     $coderef = sub { print "Boink!\n" };
  103.  
  104. Note the presence of the semicolon.  Except for the fact that the code
  105. inside isn't executed immediately, a C<sub {}> is not so much a
  106. declaration as it is an operator, like C<do{}> or C<eval{}>.  (However, no
  107. matter how many times you execute that line (unless you're in an
  108. C<eval("...")>), C<$coderef> will still have a reference to the I<SAME>
  109. anonymous subroutine.)
  110.  
  111. For those who worry about these things, the current implementation 
  112. uses shallow binding of local() variables; my() variables are not
  113. accessible.  This precludes true closures.  However, you can work 
  114. around this with a run-time (rather than a compile-time) eval():
  115.  
  116.     {
  117.     my $x = time;
  118.     $coderef = eval "sub { \$x }";
  119.     }
  120.  
  121. Normally--if you'd used just C<sub{}> or even C<eval{}>--your unew sub
  122. would only have been able to access the global $x.  But because you've
  123. used a run-time eval(), this will not only generate a brand new subroutine
  124. reference each time called, it will all grant access to the my() variable
  125. lexically above it rather than the global one.  The particular $x 
  126. accessed will be different for each new sub you create.  This mechanism
  127. yields deep binding of variables.  (If you don't know what closures, deep
  128. binding, or shallow binding are, don't worry too much about it.)
  129.  
  130. =item 5.
  131.  
  132. References are often returned by special subroutines called constructors.
  133. Perl objects are just reference a special kind of object that happens to know
  134. which package it's associated with.  Constructors are just special
  135. subroutines that know how to create that association.  They do so by
  136. starting with an ordinary reference, and it remains an ordinary reference
  137. even while it's also being an object.  Constructors are customarily
  138. named new(), but don't have to be:
  139.  
  140.     $objref = new Doggie (Tail => 'short', Ears => 'long');
  141.  
  142. =item 6.
  143.  
  144. References of the appropriate type can spring into existence if you
  145. dereference them in a context that assumes they exist.  Since we haven't
  146. talked about dereferencing yet, we can't show you any examples yet.
  147.  
  148. =back
  149.  
  150. That's it for creating references.  By now you're probably dying to
  151. know how to use references to get back to your long-lost data.  There
  152. are several basic methods.
  153.  
  154. =over 4
  155.  
  156. =item 1.
  157.  
  158. Anywhere you'd put an identifier as part of a variable or subroutine
  159. name, you can replace the identifier with a simple scalar variable
  160. containing a reference of the correct type:
  161.  
  162.     $bar = $$scalarref;
  163.     push(@$arrayref, $filename);
  164.     $$arrayref[0] = "January";
  165.     $$hashref{"KEY"} = "VALUE";
  166.     &$coderef(1,2,3);
  167.  
  168. It's important to understand that we are specifically I<NOT> dereferencing
  169. C<$arrayref[0]> or C<$hashref{"KEY"}> there.  The dereference of the
  170. scalar variable happens I<BEFORE> it does any key lookups.  Anything more
  171. complicated than a simple scalar variable must use methods 2 or 3 below.
  172. However, a "simple scalar" includes an identifier that itself uses method
  173. 1 recursively.  Therefore, the following prints "howdy".
  174.  
  175.     $refrefref = \\\"howdy";
  176.     print $$$$refrefref;
  177.  
  178. =item 2.
  179.  
  180. Anywhere you'd put an identifier as part of a variable or subroutine
  181. name, you can replace the identifier with a BLOCK returning a reference
  182. of the correct type.  In other words, the previous examples could be
  183. written like this:
  184.  
  185.     $bar = ${$scalarref};
  186.     push(@{$arrayref}, $filename);
  187.     ${$arrayref}[0] = "January";
  188.     ${$hashref}{"KEY"} = "VALUE";
  189.     &{$coderef}(1,2,3);
  190.  
  191. Admittedly, it's a little silly to use the curlies in this case, but
  192. the BLOCK can contain any arbitrary expression, in particular,
  193. subscripted expressions:
  194.  
  195.     &{ $dispatch{$index} }(1,2,3);    # call correct routine 
  196.  
  197. Because of being able to omit the curlies for the simple case of C<$$x>,
  198. people often make the mistake of viewing the dereferencing symbols as
  199. proper operators, and wonder about their precedence.  If they were,
  200. though, you could use parens instead of braces.  That's not the case.
  201. Consider the difference below; case 0 is a short-hand version of case 1,
  202. I<NOT> case 2:
  203.  
  204.     $$hashref{"KEY"}   = "VALUE";    # CASE 0
  205.     ${$hashref}{"KEY"} = "VALUE";    # CASE 1
  206.     ${$hashref{"KEY"}} = "VALUE";    # CASE 2
  207.     ${$hashref->{"KEY"}} = "VALUE";    # CASE 3
  208.  
  209. Case 2 is also deceptive in that you're accessing a variable
  210. called %hashref, not dereferencing through $hashref to the hash
  211. it's presumably referencing.  That would be case 3.
  212.  
  213. =item 3.
  214.  
  215. The case of individual array elements arises often enough that it gets
  216. cumbersome to use method 2.  As a form of syntactic sugar, the two
  217. lines like that above can be written:
  218.  
  219.     $arrayref->[0] = "January";
  220.     $hashref->{"KEY} = "VALUE";
  221.  
  222. The left side of the array can be any expression returning a reference,
  223. including a previous dereference.  Note that C<$array[$x]> is I<NOT> the
  224. same thing as C<$array-E<gt>[$x]> here:
  225.  
  226.     $array[$x]->{"foo"}->[0] = "January";
  227.  
  228. This is one of the cases we mentioned earlier in which references could
  229. spring into existence when in an lvalue context.  Before this
  230. statement, C<$array[$x]> may have been undefined.  If so, it's
  231. automatically defined with a hash reference so that we can look up
  232. C<{"foo"}> in it.  Likewise C<$array[$x]-E<gt>{"foo"}> will automatically get
  233. defined with an array reference so that we can look up C<[0]> in it.
  234.  
  235. One more thing here.  The arrow is optional I<BETWEEN> brackets
  236. subscripts, so you can shrink the above down to
  237.  
  238.     $array[$x]{"foo"}[0] = "January";
  239.  
  240. Which, in the degenerate case of using only ordinary arrays, gives you
  241. multidimensional arrays just like C's:
  242.  
  243.     $score[$x][$y][$z] += 42;
  244.  
  245. Well, okay, not entirely like C's arrays, actually.  C doesn't know how
  246. to grow its arrays on demand.  Perl does.
  247.  
  248. =item 4.
  249.  
  250. If a reference happens to be a reference to an object, then there are
  251. probably methods to access the things referred to, and you should probably
  252. stick to those methods unless you're in the class package that defines the
  253. object's methods.  In other words, be nice, and don't violate the object's
  254. encapsulation without a very good reason.  Perl does not enforce
  255. encapsulation.  We are not totalitarians here.  We do expect some basic
  256. civility though.
  257.  
  258. =back
  259.  
  260. The ref() operator may be used to determine what type of thing the
  261. reference is pointing to.  See L<perlfunc>.
  262.  
  263. The bless() operator may be used to associate a reference with a package
  264. functioning as an object class.  See L<perlobj>.
  265.  
  266. A type glob may be dereferenced the same way a reference can, since
  267. the dereference syntax always indicates the kind of reference desired.
  268. So C<${*foo}> and C<${\$foo}> both indicate the same scalar variable.
  269.  
  270. Here's a trick for interpolating a subroutine call into a string:
  271.  
  272.     print "My sub returned ${\mysub(1,2,3)}\n";
  273.  
  274. The way it works is that when the C<${...}> is seen in the double-quoted
  275. string, it's evaluated as a block.  The block executes the call to
  276. C<mysub(1,2,3)>, and then takes a reference to that.  So the whole block
  277. returns a reference to a scalar, which is then dereferenced by C<${...}>
  278. and stuck into the double-quoted string.
  279.  
  280. =head2 Symbolic references
  281.  
  282. We said that references spring into existence as necessary if they are
  283. undefined, but we didn't say what happens if a value used as a
  284. reference is already defined, but I<ISN'T> a hard reference.  If you
  285. use it as a reference in this case, it'll be treated as a symbolic
  286. reference.  That is, the value of the scalar is taken to be the I<NAME>
  287. of a variable, rather than a direct link to a (possibly) anonymous
  288. value.
  289.  
  290. People frequently expect it to work like this.  So it does.
  291.  
  292.     $name = "foo";
  293.     $$name = 1;            # Sets $foo
  294.     ${$name} = 2;        # Sets $foo
  295.     ${$name x 2} = 3;        # Sets $foofoo
  296.     $name->[0] = 4;        # Sets $foo[0]
  297.     @$name = ();        # Clears @foo
  298.     &$name();            # Calls &foo() (as in Perl 4)
  299.     $pack = "THAT";
  300.     ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
  301.  
  302. This is very powerful, and slightly dangerous, in that it's possible
  303. to intend (with the utmost sincerity) to use a hard reference, and
  304. accidentally use a symbolic reference instead.  To protect against
  305. that, you can say
  306.  
  307.     use strict 'refs';
  308.  
  309. and then only hard references will be allowed for the rest of the enclosing
  310. block.  An inner block may countermand that with 
  311.  
  312.     no strict 'refs';
  313.  
  314. Only package variables are visible to symbolic references.  Lexical
  315. variables (declared with my()) aren't in a symbol table, and thus are
  316. invisible to this mechanism.  For example:
  317.  
  318.     local($value) = 10;
  319.     $ref = \$value;
  320.     {
  321.     my $value = 20;
  322.     print $$ref;
  323.     } 
  324.  
  325. This will still print 10, not 20.  Remember that local() affects package
  326. variables, which are all "global" to the package.
  327.  
  328. =head2 Further Reading
  329.  
  330. Besides the obvious documents, source code can be instructive.
  331. Some rather pathological examples of the use of references can be found
  332. in the F<t/op/ref.t> regression test in the Perl source directory.
  333.