home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl502b.zip / pod / perlobj.pod < prev    next >
Text File  |  1995-12-28  |  14KB  |  411 lines

  1. =head1 NAME
  2.  
  3. perlobj - Perl objects
  4.  
  5. =head1 DESCRIPTION
  6.  
  7. First of all, you need to understand what references are in Perl.  See
  8. L<perlref> for that.  
  9.  
  10. Here are three very simple definitions that you should find reassuring.
  11.  
  12. =over 4
  13.  
  14. =item 1.
  15.  
  16. An object is simply a reference that happens to know which class it
  17. belongs to.
  18.  
  19. =item 2.
  20.  
  21. A class is simply a package that happens to provide methods to deal
  22. with object references.
  23.  
  24. =item 3.
  25.  
  26. A method is simply a subroutine that expects an object reference (or
  27. a package name, for static methods) as the first argument.
  28.  
  29. =back
  30.  
  31. We'll cover these points now in more depth.
  32.  
  33. =head2 An Object is Simply a Reference
  34.  
  35. Unlike say C++, Perl doesn't provide any special syntax for
  36. constructors.  A constructor is merely a subroutine that returns a
  37. reference to something "blessed" into a class, generally the
  38. class that the subroutine is defined in.  Here is a typical
  39. constructor:
  40.  
  41.     package Critter;
  42.     sub new { bless {} }
  43.  
  44. The C<{}> constructs a reference to an anonymous hash containing no 
  45. key/value pairs.  The bless() takes that reference and tells the object
  46. it references that it's now a Critter, and returns the reference.
  47. This is for convenience, since the referenced object itself knows that
  48. it has been blessed, and its reference to it could have been returned 
  49. directly, like this:
  50.  
  51.     sub new {
  52.     my $self = {};
  53.     bless $self;
  54.     return $self;
  55.     }
  56.  
  57. In fact, you often see such a thing in more complicated constructors
  58. that wish to call methods in the class as part of the construction:
  59.  
  60.     sub new {
  61.     my $self = {}
  62.     bless $self;
  63.     $self->initialize();
  64.     return $self;
  65.     }
  66.  
  67. If you care about inheritance (and you should; see L<perlmod/"Modules:
  68. Creation, Use and Abuse">), then you want to use the two-arg form of bless
  69. so that your constructors may be inherited:
  70.  
  71.     sub new {
  72.     my $class = shift;
  73.     my $self = {};
  74.     bless $self, $class
  75.     $self->initialize();
  76.     return $self;
  77.     }
  78.  
  79. Or if you expect people to call not just C<CLASS->new()> but also
  80. C<$obj->new()>, then use something like this.  The initialize()
  81. method used will be of whatever $class we blessed the 
  82. object into:
  83.  
  84.     sub new {
  85.     my $this = shift;
  86.     my $class = ref($this) || $this;
  87.     my $self = {};
  88.     bless $self, $class
  89.     $self->initialize();
  90.     return $self;
  91.     }
  92.  
  93. Within the class package, the methods will typically deal with the
  94. reference as an ordinary reference.  Outside the class package,
  95. the reference is generally treated as an opaque value that may
  96. only be accessed through the class's methods.
  97.  
  98. A constructor may re-bless a referenced object currently belonging to
  99. another class, but then the new class is responsible for all cleanup
  100. later.  The previous blessing is forgotten, as an object may only
  101. belong to one class at a time.  (Although of course it's free to 
  102. inherit methods from many classes.)
  103.  
  104. A clarification:  Perl objects are blessed.  References are not.  Objects
  105. know which package they belong to.  References do not.  The bless()
  106. function simply uses the reference in order to find the object.  Consider
  107. the following example:
  108.  
  109.     $a = {};
  110.     $b = $a;
  111.     bless $a, BLAH;
  112.     print "\$b is a ", ref($b), "\n";
  113.  
  114. This reports $b as being a BLAH, so obviously bless() 
  115. operated on the object and not on the reference.
  116.  
  117. =head2 A Class is Simply a Package
  118.  
  119. Unlike say C++, Perl doesn't provide any special syntax for class
  120. definitions.  You just use a package as a class by putting method
  121. definitions into the class.
  122.  
  123. There is a special array within each package called @ISA which says
  124. where else to look for a method if you can't find it in the current
  125. package.  This is how Perl implements inheritance.  Each element of the
  126. @ISA array is just the name of another package that happens to be a
  127. class package.  The classes are searched (depth first) for missing
  128. methods in the order that they occur in @ISA.  The classes accessible
  129. through @ISA are known as base classes of the current class. 
  130.  
  131. If a missing method is found in one of the base classes, it is cached
  132. in the current class for efficiency.  Changing @ISA or defining new
  133. subroutines invalidates the cache and causes Perl to do the lookup again.
  134.  
  135. If a method isn't found, but an AUTOLOAD routine is found, then
  136. that is called on behalf of the missing method.
  137.  
  138. If neither a method nor an AUTOLOAD routine is found in @ISA, then one
  139. last try is made for the method (or an AUTOLOAD routine) in a class
  140. called UNIVERSAL.  If that doesn't work, Perl finally gives up and
  141. complains.
  142.  
  143. Perl classes only do method inheritance.  Data inheritance is left
  144. up to the class itself.  By and large, this is not a problem in Perl,
  145. because most classes model the attributes of their object using
  146. an anonymous hash, which serves as its own little namespace to be
  147. carved up by the various classes that might want to do something
  148. with the object.
  149.  
  150. =head2 A Method is Simply a Subroutine
  151.  
  152. Unlike say C++, Perl doesn't provide any special syntax for method
  153. definition.  (It does provide a little syntax for method invocation
  154. though.  More on that later.)  A method expects its first argument
  155. to be the object or package it is being invoked on.  There are just two
  156. types of methods, which we'll call static and virtual, in honor of
  157. the two C++ method types they most closely resemble.
  158.  
  159. A static method expects a class name as the first argument.  It
  160. provides functionality for the class as a whole, not for any individual
  161. object belonging to the class.  Constructors are typically static
  162. methods.  Many static methods simply ignore their first argument, since
  163. they already know what package they're in, and don't care what package
  164. they were invoked via.  (These aren't necessarily the same, since
  165. static methods follow the inheritance tree just like ordinary virtual
  166. methods.)  Another typical use for static methods is to look up an
  167. object by name:
  168.  
  169.     sub find {
  170.     my ($class, $name) = @_;
  171.     $objtable{$name};
  172.     }
  173.  
  174. A virtual method expects an object reference as its first argument.
  175. Typically it shifts the first argument into a "self" or "this" variable,
  176. and then uses that as an ordinary reference.
  177.  
  178.     sub display {
  179.     my $self = shift;
  180.     my @keys = @_ ? @_ : sort keys %$self;
  181.     foreach $key (@keys) {
  182.         print "\t$key => $self->{$key}\n";
  183.     }
  184.     }
  185.  
  186. =head2 Method Invocation
  187.  
  188. There are two ways to invoke a method, one of which you're already
  189. familiar with, and the other of which will look familiar.  Perl 4
  190. already had an "indirect object" syntax that you use when you say
  191.  
  192.     print STDERR "help!!!\n";
  193.  
  194. This same syntax can be used to call either static or virtual methods.
  195. We'll use the two methods defined above, the static method to lookup
  196. an object reference and the virtual method to print out its attributes.
  197.  
  198.     $fred = find Critter "Fred";
  199.     display $fred 'Height', 'Weight';
  200.  
  201. These could be combined into one statement by using a BLOCK in the
  202. indirect object slot:
  203.  
  204.     display {find Critter "Fred"} 'Height', 'Weight';
  205.  
  206. For C++ fans, there's also a syntax using -> notation that does exactly
  207. the same thing.  The parentheses are required if there are any arguments.
  208.  
  209.     $fred = Critter->find("Fred");
  210.     $fred->display('Height', 'Weight');
  211.  
  212. or in one statement,
  213.  
  214.     Critter->find("Fred")->display('Height', 'Weight');
  215.  
  216. There are times when one syntax is more readable, and times when the
  217. other syntax is more readable.  The indirect object syntax is less
  218. cluttered, but it has the same ambiguity as ordinary list operators.
  219. Indirect object method calls are parsed using the same rule as list
  220. operators: "If it looks like a function, it is a function".  (Presuming
  221. for the moment that you think two words in a row can look like a
  222. function name.  C++ programmers seem to think so with some regularity,
  223. especially when the first word is "new".)  Thus, the parens of
  224.  
  225.     new Critter ('Barney', 1.5, 70)
  226.  
  227. are assumed to surround ALL the arguments of the method call, regardless
  228. of what comes after.  Saying
  229.  
  230.     new Critter ('Bam' x 2), 1.4, 45
  231.  
  232. would be equivalent to
  233.  
  234.     Critter->new('Bam' x 2), 1.4, 45
  235.  
  236. which is unlikely to do what you want.
  237.  
  238. There are times when you wish to specify which class's method to use.
  239. In this case, you can call your method as an ordinary subroutine
  240. call, being sure to pass the requisite first argument explicitly:
  241.  
  242.     $fred =  MyCritter::find("Critter", "Fred");
  243.     MyCritter::display($fred, 'Height', 'Weight');
  244.  
  245. Note however, that this does not do any inheritance.  If you merely
  246. wish to specify that Perl should I<START> looking for a method in a
  247. particular package, use an ordinary method call, but qualify the method
  248. name with the package like this:
  249.  
  250.     $fred = Critter->MyCritter::find("Fred");
  251.     $fred->MyCritter::display('Height', 'Weight');
  252.  
  253. If you're trying to control where the method search begins I<and> you're
  254. executing in the class itself, then you may use the SUPER pseudoclass,
  255. which says to start looking in your base class's @ISA list without having
  256. to explicitly name it:
  257.  
  258.     $self->SUPER::display('Height', 'Weight');
  259.  
  260. Please note that the C<SUPER::> construct is I<only> meaningful within the
  261. class.
  262.  
  263. Sometimes you want to call a method when you don't know the method name
  264. ahead of time.  You can use the arrow form, replacing the method name
  265. with a simple scalar variable containing the method name:
  266.  
  267.     $method = $fast ? "findfirst" : "findbest";
  268.     $fred->$method(@args);
  269.  
  270. =head2 Destructors
  271.  
  272. When the last reference to an object goes away, the object is
  273. automatically destroyed.  (This may even be after you exit, if you've
  274. stored references in global variables.)  If you want to capture control
  275. just before the object is freed, you may define a DESTROY method in
  276. your class.  It will automatically be called at the appropriate moment,
  277. and you can do any extra cleanup you need to do.
  278.  
  279. Perl doesn't do nested destruction for you.  If your constructor
  280. reblessed a reference from one of your base classes, your DESTROY may
  281. need to call DESTROY for any base classes that need it.  But this only
  282. applies to reblessed objects--an object reference that is merely
  283. I<CONTAINED> in the current object will be freed and destroyed
  284. automatically when the current object is freed.
  285.  
  286. =head2 WARNING
  287.  
  288. An indirect object is limited to a name, a scalar variable, or a block,
  289. because it would have to do too much lookahead otherwise, just like any
  290. other postfix dereference in the language.  The left side of -> is not so
  291. limited, because it's an infix operator, not a postfix operator.  
  292.  
  293. That means that below, A and B are equivalent to each other, and C and D
  294. are equivalent, but AB and CD are different:
  295.  
  296.     A: method $obref->{"fieldname"} 
  297.     B: (method $obref)->{"fieldname"}
  298.     C: $obref->{"fieldname"}->method() 
  299.     D: method {$obref->{"fieldname"}}
  300.  
  301. =head2 Summary
  302.  
  303. That's about all there is to it.  Now you just need to go off and buy a
  304. book about object-oriented design methodology, and bang your forehead
  305. with it for the next six months or so.
  306.  
  307. =head2 Two-Phased Garbage Collection
  308.  
  309. For most purposes, Perl uses a fast and simple reference-based
  310. garbage collection system.  For this reason, there's an extra
  311. dereference going on at some level, so if you haven't built
  312. your Perl executable using your C compiler's C<-O> flag, performance
  313. will suffer.  If you I<have> built Perl with C<cc -O>, then this
  314. probably won't matter.
  315.  
  316. A more serious concern is that unreachable memory with a non-zero
  317. reference count will not normally get freed.  Therefore, this is a bad
  318. idea:  
  319.  
  320.     {
  321.     my $a;
  322.     $a = \$a;
  323.     } 
  324.  
  325. Even thought $a I<should> go away, it can't.  When building recursive data
  326. structures, you'll have to break the self-reference yourself explicitly
  327. if you don't care to leak.  For example, here's a self-referential
  328. node such as one might use in a sophisticated tree structure:
  329.  
  330.     sub new_node {
  331.     my $self = shift;
  332.     my $class = ref($self) || $self;
  333.     my $node = {};
  334.     $node->{LEFT} = $node->{RIGHT} = $node;
  335.     $node->{DATA} = [ @_ ];
  336.     return bless $node => $class;
  337.     } 
  338.  
  339. If you create nodes like that, they (currently) won't go away unless you
  340. break their self reference yourself.  (In other words, this is not to be
  341. construed as a feature, and you shouldn't depend on it.)
  342.  
  343. Almost.
  344.  
  345. When an interpreter thread finally shuts down (usually when your program
  346. exits), then a rather costly but complete mark-and-sweep style of garbage
  347. collection is performed, and everything allocated by that thread gets
  348. destroyed.  This is essential to support Perl as an embedded or a
  349. multithreadable language.  For example, this program demonstrates Perl's
  350. two-phased garbage collection:
  351.  
  352.     #!/usr/bin/perl 
  353.     package Subtle;
  354.  
  355.     sub new {
  356.     my $test;
  357.     $test = \$test;
  358.     warn "CREATING " . \$test;
  359.     return bless \$test;
  360.     } 
  361.  
  362.     sub DESTROY {
  363.     my $self = shift;
  364.     warn "DESTROYING $self";
  365.     } 
  366.  
  367.     package main;
  368.  
  369.     warn "starting program";
  370.     {
  371.     my $a = Subtle->new;
  372.     my $b = Subtle->new;
  373.     $$a = 0;  # break selfref
  374.     warn "leaving block";
  375.     } 
  376.  
  377.     warn "just exited block";
  378.     warn "time to die...";
  379.     exit;
  380.  
  381. When run as F</tmp/test>, the following output is produced:
  382.  
  383.     starting program at /tmp/test line 18.
  384.     CREATING SCALAR(0x8e5b8) at /tmp/test line 7.
  385.     CREATING SCALAR(0x8e57c) at /tmp/test line 7.
  386.     leaving block at /tmp/test line 23.
  387.     DESTROYING Subtle=SCALAR(0x8e5b8) at /tmp/test line 13.
  388.     just exited block at /tmp/test line 26.
  389.     time to die... at /tmp/test line 27.
  390.     DESTROYING Subtle=SCALAR(0x8e57c) during global destruction.
  391.  
  392. Notice that "global destruction" bit there?  That's the thread
  393. garbage collector reaching the unreachable.  
  394.  
  395. Objects are always destructed, even when regular refs aren't and in fact
  396. are destructed in a separate pass before ordinary refs just to try to
  397. prevent object destructors from using refs that have been themselves
  398. destructed.  Plain refs are only garbage collected if the destruct level
  399. is greater than 0.  You can test the higher levels of global destruction
  400. by setting the PERL_DESTRUCT_LEVEL environment variable, presuming
  401. C<-DDEBUGGING> was enabled during perl build time.
  402.  
  403. A more complete garbage collection strategy will be implemented
  404. at a future date.
  405.  
  406. =head1 SEE ALSO
  407.  
  408. You should also check out L<perlbot> for other object tricks, traps, and tips, 
  409. as well as L<perlmod> for some style guides on constructing both modules
  410. and classes.
  411.