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

  1. <!-- $RCSfile$$Revision$$Date$ -->
  2. <!-- $Log$ -->
  3. <HTML>
  4. <TITLE> PERLOBJ </TITLE>
  5. <h2>NAME</h2>
  6. perlobj - Perl objects
  7. <p><h2>DESCRIPTION</h2>
  8. First of all, you need to understand what references are in Perl.  See
  9.  
  10. <A HREF="perlref.html">
  11. the perlref manpage</A>
  12.  for that.  
  13. <p>Here are three very simple definitions that you should find reassuring.
  14. <p>
  15. <dl>
  16.  
  17. <dt><b><A NAME="perlcall_48">1.</A></b>
  18. <dd>
  19. An object is simply a reference that happens to know which class it
  20. belongs to.
  21. <p></dd>
  22.  
  23. <dt><b><A NAME="perlcall_49">2.</A></b>
  24. <dd>
  25. A class is simply a package that happens to provide methods to deal
  26. with object references.
  27. <p></dd>
  28.  
  29. <dt><b><A NAME="perlcall_50">3.</A></b>
  30. <dd>
  31. A method is simply a subroutine that expects an object reference (or
  32. a package name, for static methods) as the first argument.
  33. <p></dd>
  34.  
  35. </dl>
  36.  
  37. We'll cover these points now in more depth.
  38. <p><h3>An Object is Simply a Reference</h3>
  39. Unlike say C++, Perl doesn't provide any special syntax for
  40. constructors.  A constructor is merely a subroutine that returns a
  41. reference that has been "blessed" into a class, generally the
  42. class that the subroutine is defined in.  Here is a typical
  43. constructor:
  44. <p><pre>
  45.         package Critter;
  46.         sub new { bless {} }
  47. </pre>
  48. The <B>{}</B> constructs a reference to an anonymous hash containing no 
  49. key/value pairs.  The bless() takes that reference and tells the object
  50. it references that it's now a Critter, and returns the reference.
  51. This is for convenience, since the referenced object itself knows that
  52. it has been blessed, and its reference to it could have been returned 
  53. directly, like this:
  54. <p><pre>
  55.         sub new {
  56.         my $self = {};
  57.         bless $self;
  58.         return $self;
  59.         }
  60. </pre>
  61. In fact, you often see such a thing in more complicated constructors
  62. that wish to call methods in the class as part of the construction:
  63. <p><pre>
  64.         sub new {
  65.         my $self = {}
  66.         bless $self;
  67.         $self->initialize();
  68.         $self;
  69.         }
  70. </pre>
  71. Within the class package, the methods will typically deal with the
  72. reference as an ordinary reference.  Outside the class package,
  73. the reference is generally treated as an opaque value that may
  74. only be accessed through the class's methods.
  75. <p>A constructor may rebless a referenced object currently belonging to
  76. another class, but then the new class is responsible for all cleanup
  77. later.  The previous blessing is forgotten, as an object may only
  78. belong to one class at a time.  (Although of course it's free to 
  79. inherit methods from many classes.)
  80. <p>A clarification:  Perl objects are blessed.  References are not.  Objects
  81. know which package they belong to.  References do not.  The bless()
  82. function simply uses the reference in order to find the object.  Consider
  83. the following example:
  84. <p><pre>
  85.         $a = {};
  86.         $b = $a;
  87.         bless $a, BLAH;
  88.         print "\$b is a ", ref($b), "\n";
  89. </pre>
  90. This reports $b as being a BLAH, so obviously bless() 
  91. operated on the object and not on the reference.
  92. <p><h3>A Class is Simply a Package</h3>
  93. Unlike say C++, Perl doesn't provide any special syntax for class
  94. definitions.  You just use a package as a class by putting method
  95. definitions into the class.
  96. <p>There is a special array within each package called @ISA which says
  97. where else to look for a method if you can't find it in the current
  98. package.  This is how Perl implements inheritance.  Each element of the
  99. @ISA array is just the name of another package that happens to be a
  100. class package.  The classes are searched (depth first) for missing
  101. methods in the order that they occur in @ISA.  The classes accessible
  102. through @ISA are known as base classes of the current class.
  103. <p>If a missing method is found in one of the base classes, it is cached
  104. in the current class for efficiency.  Changing @ISA or defining new
  105. subroutines invalidates the cache and causes Perl to do the lookup again.
  106. <p>If a method isn't found, but an AUTOLOAD routine is found, then
  107. that is called on behalf of the missing method.
  108. <p>If neither a method nor an AUTOLOAD routine is found in @ISA, then one
  109. last try is made for the method (or an AUTOLOAD routine) in a class
  110. called UNIVERSAL.  If that doesn't work, Perl finally gives up and
  111. complains.
  112. <p>Perl classes only do method inheritance.  Data inheritance is left
  113. up to the class itself.  By and large, this is not a problem in Perl,
  114. because most classes model the attributes of their object using
  115. an anonymous hash, which serves as its own little namespace to be
  116. carved up by the various classes that might want to do something
  117. with the object.
  118. <p><h3>A Method is Simply a Subroutine</h3>
  119. Unlike say C++, Perl doesn't provide any special syntax for method
  120. definition.  (It does provide a little syntax for method invocation
  121. though.  More on that later.)  A method expects its first argument
  122. to be the object or package it is being invoked on.  There are just two
  123. types of methods, which we'll call static and virtual, in honor of
  124. the two C++ method types they most closely resemble.
  125. <p>A static method expects a class name as the first argument.  It
  126. provides functionality for the class as a whole, not for any individual
  127. object belonging to the class.  Constructors are typically static
  128. methods.  Many static methods simply ignore their first argument, since
  129. they already know what package they're in, and don't care what package
  130. they were invoked via.  (These aren't necessarily the same, since
  131. static methods follow the inheritance tree just like ordinary virtual
  132. methods.)  Another typical use for static methods is to look up an
  133. object by name:
  134. <p><pre>
  135.         sub find {
  136.         my ($class, $name) = @_;
  137.         $objtable{$name};
  138.         }
  139. </pre>
  140. A virtual method expects an object reference as its first argument.
  141. Typically it shifts the first argument into a "self" or "this" variable,
  142. and then uses that as an ordinary reference.
  143. <p><pre>
  144.         sub display {
  145.         my $self = shift;
  146.         my @keys = @_ ? @_ : sort keys %$self;
  147.         foreach $key (@keys) {
  148.             print "\t$key => $self->{$key}\n";
  149.         }
  150.         }
  151. </pre>
  152. <h3>Method Invocation</h3>
  153. There are two ways to invoke a method, one of which you're already
  154. familiar with, and the other of which will look familiar.  Perl 4
  155. already had an "indirect object" syntax that you use when you say
  156. <p><pre>
  157.         print STDERR "help!!!\n";
  158. </pre>
  159. This same syntax can be used to call either static or virtual methods.
  160. We'll use the two methods defined above, the static method to lookup
  161. an object reference and the virtual method to print out its attributes.
  162. <p><pre>
  163.         $fred = find Critter "Fred";
  164.         display $fred 'Height', 'Weight';
  165. </pre>
  166. These could be combined into one statement by using a BLOCK in the
  167. indirect object slot:
  168. <p><pre>
  169.         display {find Critter "Fred"} 'Height', 'Weight';
  170. </pre>
  171. For C++ fans, there's also a syntax using -> notation that does exactly
  172. the same thing.  The parentheses are required if there are any arguments.
  173. <p><pre>
  174.         $fred = Critter->find("Fred");
  175.         $fred->display('Height', 'Weight');
  176. </pre>
  177. or in one statement,
  178. <p><pre>
  179.         Critter->find("Fred")->display('Height', 'Weight');
  180. </pre>
  181. There are times when one syntax is more readable, and times when the
  182. other syntax is more readable.  The indirect object syntax is less
  183. cluttered, but it has the same ambiguity as ordinary list operators.
  184. Indirect object method calls are parsed using the same rule as list
  185. operators: "If it looks like a function, it is a function".  (Presuming
  186. for the moment that you think two words in a row can look like a
  187. function name.  C++ programmers seem to think so with some regularity,
  188. especially when the first word is "new".)  Thus, the parens of
  189. <p><pre>
  190.         new Critter ('Barney', 1.5, 70)
  191. </pre>
  192. are assumed to surround ALL the arguments of the method call, regardless
  193. of what comes after.  Saying
  194. <p><pre>
  195.         new Critter ('Bam' x 2), 1.4, 45
  196. </pre>
  197. would be equivalent to
  198. <p><pre>
  199.         Critter->new('Bam' x 2), 1.4, 45
  200. </pre>
  201. which is unlikely to do what you want.
  202. <p>There are times when you wish to specify which class's method to use.
  203. In this case, you can call your method as an ordinary subroutine
  204. call, being sure to pass the requisite first argument explicitly:
  205. <p><pre>
  206.         $fred =  MyCritter::find("Critter", "Fred");
  207.         MyCritter::display($fred, 'Height', 'Weight');
  208. </pre>
  209. Note however, that this does not do any inheritance.  If you merely
  210. wish to specify that Perl should <I>START</I> looking for a method in a
  211. particular package, use an ordinary method call, but qualify the method
  212. name with the package like this:
  213. <p><pre>
  214.         $fred = Critter->MyCritter::find("Fred");
  215.         $fred->MyCritter::display('Height', 'Weight');
  216. </pre>
  217. <h3>Destructors</h3>
  218. When the last reference to an object goes away, the object is
  219. automatically destroyed.  (This may even be after you exit, if you've
  220. stored references in global variables.)  If you want to capture control
  221. just before the object is freed, you may define a DESTROY method in
  222. your class.  It will automatically be called at the appropriate moment,
  223. and you can do any extra cleanup you need to do.
  224. <p>Perl doesn't do nested destruction for you.  If your constructor
  225. reblessed a reference from one of your base classes, your DESTROY may
  226. need to call DESTROY for any base classes that need it.  But this only
  227. applies to reblessed objects--an object reference that is merely
  228. <I>CONTAINED</I> in the current object will be freed and destroyed
  229. automatically when the current object is freed.
  230. <p><h3>Summary</h3>
  231. That's about all there is to it.  Now you just need to go off and buy a
  232. book about object-oriented design methodology, and bang your forehead
  233. with it for the next six months or so.
  234. <p><h2>SEE ALSO</h2>
  235. You should also check out 
  236. <A HREF="perlbot.html">
  237. the perlbot manpage</A>
  238.  for other object tricks, traps, and tips.<p>