home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 2 / RISC_DISC_2.iso / pd_share / utilities / cli / perl / !Perl / Manual / perlref < prev    next >
Encoding:
Text File  |  1995-04-18  |  14.5 KB  |  344 lines

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