home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 May / Chip_2000-05_cd1.bin / zkuste / Perl / ActivePerl-5.6.0.613.msi / 䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥 / _487dfba76b6fbfe3d68425428672fd94 < prev    next >
Text File  |  2000-03-23  |  81KB  |  1,723 lines

  1. <HTML>
  2. <HEAD>
  3. <TITLE>perltoot - Tom's object-oriented tutorial for perl</TITLE>
  4. <LINK REL="stylesheet" HREF="../../Active.css" TYPE="text/css">
  5. <LINK REV="made" HREF="mailto:">
  6. </HEAD>
  7.  
  8. <BODY>
  9. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  10. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  11. <STRONG><P CLASS=block> perltoot - Tom's object-oriented tutorial for perl</P></STRONG>
  12. </TD></TR>
  13. </TABLE>
  14.  
  15. <A NAME="__index__"></A>
  16. <!-- INDEX BEGIN -->
  17.  
  18. <UL>
  19.  
  20.     <LI><A HREF="#name">NAME</A></LI>
  21.     <LI><A HREF="#description">DESCRIPTION</A></LI>
  22.     <LI><A HREF="#creating a class">Creating a Class</A></LI>
  23.     <UL>
  24.  
  25.         <LI><A HREF="#object representation">Object Representation</A></LI>
  26.         <LI><A HREF="#class interface">Class Interface</A></LI>
  27.         <LI><A HREF="#constructors and instance methods">Constructors and Instance Methods</A></LI>
  28.         <LI><A HREF="#planning for the future: better constructors">Planning for the Future: Better Constructors</A></LI>
  29.         <LI><A HREF="#destructors">Destructors</A></LI>
  30.         <LI><A HREF="#other object methods">Other Object Methods</A></LI>
  31.     </UL>
  32.  
  33.     <LI><A HREF="#class data">Class Data</A></LI>
  34.     <UL>
  35.  
  36.         <LI><A HREF="#accessing class data">Accessing Class Data</A></LI>
  37.         <LI><A HREF="#debugging methods">Debugging Methods</A></LI>
  38.         <LI><A HREF="#class destructors">Class Destructors</A></LI>
  39.         <LI><A HREF="#documenting the interface">Documenting the Interface</A></LI>
  40.     </UL>
  41.  
  42.     <LI><A HREF="#aggregation">Aggregation</A></LI>
  43.     <LI><A HREF="#inheritance">Inheritance</A></LI>
  44.     <UL>
  45.  
  46.         <LI><A HREF="#overridden methods">Overridden Methods</A></LI>
  47.         <LI><A HREF="#multiple inheritance">Multiple Inheritance</A></LI>
  48.         <LI><A HREF="#universal: the root of all objects">UNIVERSAL: The Root of All Objects</A></LI>
  49.     </UL>
  50.  
  51.     <LI><A HREF="#alternate object representations">Alternate Object Representations</A></LI>
  52.     <UL>
  53.  
  54.         <LI><A HREF="#arrays as objects">Arrays as Objects</A></LI>
  55.         <LI><A HREF="#closures as objects">Closures as Objects</A></LI>
  56.     </UL>
  57.  
  58.     <LI><A HREF="#autoload: proxy methods">AUTOLOAD: Proxy Methods</A></LI>
  59.     <UL>
  60.  
  61.         <LI><A HREF="#autoloaded data methods">Autoloaded Data Methods</A></LI>
  62.         <LI><A HREF="#inherited autoloaded data methods">Inherited Autoloaded Data Methods</A></LI>
  63.     </UL>
  64.  
  65.     <LI><A HREF="#metaclassical tools">Metaclassical Tools</A></LI>
  66.     <UL>
  67.  
  68.         <LI><A HREF="#class::struct">Class::Struct</A></LI>
  69.         <LI><A HREF="#data members as variables">Data Members as Variables</A></LI>
  70.         <LI><A HREF="#notes">NOTES</A></LI>
  71.         <LI><A HREF="#object terminology">Object Terminology</A></LI>
  72.     </UL>
  73.  
  74.     <LI><A HREF="#see also">SEE ALSO</A></LI>
  75.     <LI><A HREF="#author and copyright">AUTHOR AND COPYRIGHT</A></LI>
  76.     <LI><A HREF="#copyright">COPYRIGHT</A></LI>
  77.     <UL>
  78.  
  79.         <LI><A HREF="#acknowledgments">Acknowledgments</A></LI>
  80.     </UL>
  81.  
  82. </UL>
  83. <!-- INDEX END -->
  84.  
  85. <HR>
  86. <P>
  87. <H1><A NAME="name">NAME</A></H1>
  88. <P>perltoot - Tom's object-oriented tutorial for perl</P>
  89. <P>
  90. <HR>
  91. <H1><A NAME="description">DESCRIPTION</A></H1>
  92. <P>Object-oriented programming is a big seller these days.  Some managers
  93. would rather have objects than sliced bread.  Why is that?  What's so
  94. special about an object?  Just what <EM>is</EM> an object anyway?</P>
  95. <P>An object is nothing but a way of tucking away complex behaviours into
  96. a neat little easy-to-use bundle.  (This is what professors call
  97. abstraction.) Smart people who have nothing to do but sit around for
  98. weeks on end figuring out really hard problems make these nifty
  99. objects that even regular people can use. (This is what professors call
  100. software reuse.)  Users (well, programmers) can play with this little
  101. bundle all they want, but they aren't to open it up and mess with the
  102. insides.  Just like an expensive piece of hardware, the contract says
  103. that you void the warranty if you muck with the cover.  So don't do that.</P>
  104. <P>The heart of objects is the class, a protected little private namespace
  105. full of data and functions.  A class is a set of related routines that
  106. addresses some problem area.  You can think of it as a user-defined type.
  107. The Perl package mechanism, also used for more traditional modules,
  108. is used for class modules as well.  Objects ``live'' in a class, meaning
  109. that they belong to some package.</P>
  110. <P>More often than not, the class provides the user with little bundles.
  111. These bundles are objects.  They know whose class they belong to,
  112. and how to behave.  Users ask the class to do something, like ``give
  113. me an object.''  Or they can ask one of these objects to do something.
  114. Asking a class to do something for you is calling a <EM>class method</EM>.
  115. Asking an object to do something for you is calling an <EM>object method</EM>.
  116. Asking either a class (usually) or an object (sometimes) to give you
  117. back an object is calling a <EM>constructor</EM>, which is just a
  118. kind of method.</P>
  119. <P>That's all well and good, but how is an object different from any other
  120. Perl data type?  Just what is an object <EM>really</EM>; that is, what's its
  121. fundamental type?  The answer to the first question is easy.  An object
  122. is different from any other data type in Perl in one and only one way:
  123. you may dereference it using not merely string or numeric subscripts
  124. as with simple arrays and hashes, but with named subroutine calls.
  125. In a word, with <EM>methods</EM>.</P>
  126. <P>The answer to the second question is that it's a reference, and not just
  127. any reference, mind you, but one whose referent has been <EM>bless</EM>()ed
  128. into a particular class (read: package).  What kind of reference?  Well,
  129. the answer to that one is a bit less concrete.  That's because in Perl
  130. the designer of the class can employ any sort of reference they'd like
  131. as the underlying intrinsic data type.  It could be a scalar, an array,
  132. or a hash reference.  It could even be a code reference.  But because
  133. of its inherent flexibility, an object is usually a hash reference.</P>
  134. <P>
  135. <HR>
  136. <H1><A NAME="creating a class">Creating a Class</A></H1>
  137. <P>Before you create a class, you need to decide what to name it.  That's
  138. because the class (package) name governs the name of the file used to
  139. house it, just as with regular modules.  Then, that class (package)
  140. should provide one or more ways to generate objects.  Finally, it should
  141. provide mechanisms to allow users of its objects to indirectly manipulate
  142. these objects from a distance.</P>
  143. <P>For example, let's make a simple Person class module.  It gets stored in
  144. the file Person.pm.  If it were called a Happy::Person class, it would
  145. be stored in the file Happy/Person.pm, and its package would become
  146. Happy::Person instead of just Person.  (On a personal computer not
  147. running Unix or Plan 9, but something like MacOS or VMS, the directory
  148. separator may be different, but the principle is the same.)  Do not assume
  149. any formal relationship between modules based on their directory names.
  150. This is merely a grouping convenience, and has no effect on inheritance,
  151. variable accessibility, or anything else.</P>
  152. <P>For this module we aren't going to use Exporter, because we're
  153. a well-behaved class module that doesn't export anything at all.
  154. In order to manufacture objects, a class needs to have a <EM>constructor
  155. method</EM>.  A constructor gives you back not just a regular data type,
  156. but a brand-new object in that class.  This magic is taken care of by
  157. the <A HREF="../../lib/Pod/perlfunc.html#item_bless"><CODE>bless()</CODE></A> function, whose sole purpose is to enable its referent to
  158. be used as an object.  Remember: being an object really means nothing
  159. more than that methods may now be called against it.</P>
  160. <P>While a constructor may be named anything you'd like, most Perl
  161. programmers seem to like to call theirs new().  However, <CODE>new()</CODE> is not
  162. a reserved word, and a class is under no obligation to supply such.
  163. Some programmers have also been known to use a function with
  164. the same name as the class as the constructor.</P>
  165. <P>
  166. <H2><A NAME="object representation">Object Representation</A></H2>
  167. <P>By far the most common mechanism used in Perl to represent a Pascal
  168. record, a C struct, or a C++ class is an anonymous hash.  That's because a
  169. hash has an arbitrary number of data fields, each conveniently accessed by
  170. an arbitrary name of your own devising.</P>
  171. <P>If you were just doing a simple
  172. struct-like emulation, you would likely go about it something like this:</P>
  173. <PRE>
  174.     $rec = {
  175.         name  => "Jason",
  176.         age   => 23,
  177.         peers => [ "Norbert", "Rhys", "Phineas"],
  178.     };</PRE>
  179. <P>If you felt like it, you could add a bit of visual distinction
  180. by up-casing the hash keys:</P>
  181. <PRE>
  182.     $rec = {
  183.         NAME  => "Jason",
  184.         AGE   => 23,
  185.         PEERS => [ "Norbert", "Rhys", "Phineas"],
  186.     };</PRE>
  187. <P>And so you could get at <CODE>$rec->{NAME}</CODE> to find ``Jason'', or
  188. <CODE>@{ $rec->{PEERS} }</CODE> to get at ``Norbert'', ``Rhys'', and ``Phineas''.
  189. (Have you ever noticed how many 23-year-old programmers seem to
  190. be named ``Jason'' these days? :-)</P>
  191. <P>This same model is often used for classes, although it is not considered
  192. the pinnacle of programming propriety for folks from outside the
  193. class to come waltzing into an object, brazenly accessing its data
  194. members directly.  Generally speaking, an object should be considered
  195. an opaque cookie that you use <EM>object methods</EM> to access.  Visually,
  196. methods look like you're dereffing a reference using a function name
  197. instead of brackets or braces.</P>
  198. <P>
  199. <H2><A NAME="class interface">Class Interface</A></H2>
  200. <P>Some languages provide a formal syntactic interface to a class's methods,
  201. but Perl does not.  It relies on you to read the documentation of each
  202. class.  If you try to call an undefined method on an object, Perl won't
  203. complain, but the program will trigger an exception while it's running.
  204. Likewise, if you call a method expecting a prime number as its argument
  205. with a non-prime one instead, you can't expect the compiler to catch this.
  206. (Well, you can expect it all you like, but it's not going to happen.)</P>
  207. <P>Let's suppose you have a well-educated user of your Person class,
  208. someone who has read the docs that explain the prescribed
  209. interface.  Here's how they might use the Person class:</P>
  210. <PRE>
  211.     use Person;</PRE>
  212. <PRE>
  213.     $him = Person->new();
  214.     $him->name("Jason");
  215.     $him->age(23);
  216.     $him->peers( "Norbert", "Rhys", "Phineas" );</PRE>
  217. <PRE>
  218.     push @All_Recs, $him;  # save object in array for later</PRE>
  219. <PRE>
  220.     printf "%s is %d years old.\n", $him->name, $him->age;
  221.     print "His peers are: ", join(", ", $him->peers), "\n";</PRE>
  222. <PRE>
  223.     printf "Last rec's name is %s\n", $All_Recs[-1]->name;</PRE>
  224. <P>As you can see, the user of the class doesn't know (or at least, has no
  225. business paying attention to the fact) that the object has one particular
  226. implementation or another.  The interface to the class and its objects
  227. is exclusively via methods, and that's all the user of the class should
  228. ever play with.</P>
  229. <P>
  230. <H2><A NAME="constructors and instance methods">Constructors and Instance Methods</A></H2>
  231. <P>Still, <EM>someone</EM> has to know what's in the object.  And that someone is
  232. the class.  It implements methods that the programmer uses to access
  233. the object.  Here's how to implement the Person class using the standard
  234. hash-ref-as-an-object idiom.  We'll make a class method called <CODE>new()</CODE> to
  235. act as the constructor, and three object methods called name(), age(), and
  236. <CODE>peers()</CODE> to get at per-object data hidden away in our anonymous hash.</P>
  237. <PRE>
  238.     package Person;
  239.     use strict;</PRE>
  240. <PRE>
  241.     ##################################################
  242.     ## the object constructor (simplistic version)  ##
  243.     ##################################################
  244.     sub new {
  245.         my $self  = {};
  246.         $self->{NAME}   = undef;
  247.         $self->{AGE}    = undef;
  248.         $self->{PEERS}  = [];
  249.         bless($self);           # but see below
  250.         return $self;
  251.     }</PRE>
  252. <PRE>
  253.     ##############################################
  254.     ## methods to access per-object data        ##
  255.     ##                                          ##
  256.     ## With args, they set the value.  Without  ##
  257.     ## any, they only retrieve it/them.         ##
  258.     ##############################################</PRE>
  259. <PRE>
  260.     sub name {
  261.         my $self = shift;
  262.         if (@_) { $self->{NAME} = shift }
  263.         return $self->{NAME};
  264.     }</PRE>
  265. <PRE>
  266.     sub age {
  267.         my $self = shift;
  268.         if (@_) { $self->{AGE} = shift }
  269.         return $self->{AGE};
  270.     }</PRE>
  271. <PRE>
  272.     sub peers {
  273.         my $self = shift;
  274.         if (@_) { @{ $self->{PEERS} } = @_ }
  275.         return @{ $self->{PEERS} };
  276.     }</PRE>
  277. <PRE>
  278.     1;  # so the require or use succeeds</PRE>
  279. <P>We've created three methods to access an object's data, name(), age(),
  280. and peers().  These are all substantially similar.  If called with an
  281. argument, they set the appropriate field; otherwise they return the
  282. value held by that field, meaning the value of that hash key.</P>
  283. <P>
  284. <H2><A NAME="planning for the future: better constructors">Planning for the Future: Better Constructors</A></H2>
  285. <P>Even though at this point you may not even know what it means, someday
  286. you're going to worry about inheritance.  (You can safely ignore this
  287. for now and worry about it later if you'd like.)  To ensure that this
  288. all works out smoothly, you must use the double-argument form of bless().
  289. The second argument is the class into which the referent will be blessed.
  290. By not assuming our own class as the default second argument and instead
  291. using the class passed into us, we make our constructor inheritable.</P>
  292. <P>While we're at it, let's make our constructor a bit more flexible.
  293. Rather than being uniquely a class method, we'll set it up so that
  294. it can be called as either a class method <EM>or</EM> an object
  295. method.  That way you can say:</P>
  296. <PRE>
  297.     $me  = Person->new();
  298.     $him = $me->new();</PRE>
  299. <P>To do this, all we have to do is check whether what was passed in
  300. was a reference or not.  If so, we were invoked as an object method,
  301. and we need to extract the package (class) using the <A HREF="../../lib/Pod/perlfunc.html#item_ref"><CODE>ref()</CODE></A> function.
  302. If not, we just use the string passed in as the package name
  303. for blessing our referent.</P>
  304. <PRE>
  305.     sub new {
  306.         my $proto = shift;
  307.         my $class = ref($proto) || $proto;
  308.         my $self  = {};
  309.         $self->{NAME}   = undef;
  310.         $self->{AGE}    = undef;
  311.         $self->{PEERS}  = [];
  312.         bless ($self, $class);
  313.         return $self;
  314.     }</PRE>
  315. <P>That's about all there is for constructors.  These methods bring objects
  316. to life, returning neat little opaque bundles to the user to be used in
  317. subsequent method calls.</P>
  318. <P>
  319. <H2><A NAME="destructors">Destructors</A></H2>
  320. <P>Every story has a beginning and an end.  The beginning of the object's
  321. story is its constructor, explicitly called when the object comes into
  322. existence.  But the ending of its story is the <EM>destructor</EM>, a method
  323. implicitly called when an object leaves this life.  Any per-object
  324. clean-up code is placed in the destructor, which must (in Perl) be called
  325. DESTROY.</P>
  326. <P>If constructors can have arbitrary names, then why not destructors?
  327. Because while a constructor is explicitly called, a destructor is not.
  328. Destruction happens automatically via Perl's garbage collection (GC)
  329. system, which is a quick but somewhat lazy reference-based GC system.
  330. To know what to call, Perl insists that the destructor be named DESTROY.
  331. Perl's notion of the right time to call a destructor is not well-defined
  332. currently, which is why your destructors should not rely on when they are
  333. called.</P>
  334. <P>Why is DESTROY in all caps?  Perl on occasion uses purely uppercase
  335. function names as a convention to indicate that the function will
  336. be automatically called by Perl in some way.  Others that are called
  337. implicitly include BEGIN, END, AUTOLOAD, plus all methods used by
  338. tied objects, described in <A HREF="../../lib/Pod/perltie.html">the perltie manpage</A>.</P>
  339. <P>In really good object-oriented programming languages, the user doesn't
  340. care when the destructor is called.  It just happens when it's supposed
  341. to.  In low-level languages without any GC at all, there's no way to
  342. depend on this happening at the right time, so the programmer must
  343. explicitly call the destructor to clean up memory and state, crossing
  344. their fingers that it's the right time to do so.   Unlike C++, an
  345. object destructor is nearly never needed in Perl, and even when it is,
  346. explicit invocation is uncalled for.  In the case of our Person class,
  347. we don't need a destructor because Perl takes care of simple matters
  348. like memory deallocation.</P>
  349. <P>The only situation where Perl's reference-based GC won't work is
  350. when there's a circularity in the data structure, such as:</P>
  351. <PRE>
  352.     $this->{WHATEVER} = $this;</PRE>
  353. <P>In that case, you must delete the self-reference manually if you expect
  354. your program not to leak memory.  While admittedly error-prone, this is
  355. the best we can do right now.  Nonetheless, rest assured that when your
  356. program is finished, its objects' destructors are all duly called.
  357. So you are guaranteed that an object <EM>eventually</EM> gets properly
  358. destroyed, except in the unique case of a program that never exits.
  359. (If you're running Perl embedded in another application, this full GC
  360. pass happens a bit more frequently--whenever a thread shuts down.)</P>
  361. <P>
  362. <H2><A NAME="other object methods">Other Object Methods</A></H2>
  363. <P>The methods we've talked about so far have either been constructors or
  364. else simple ``data methods'', interfaces to data stored in the object.
  365. These are a bit like an object's data members in the C++ world, except
  366. that strangers don't access them as data.  Instead, they should only
  367. access the object's data indirectly via its methods.  This is an
  368. important rule: in Perl, access to an object's data should <EM>only</EM>
  369. be made through methods.</P>
  370. <P>Perl doesn't impose restrictions on who gets to use which methods.
  371. The public-versus-private distinction is by convention, not syntax.
  372. (Well, unless you use the Alias module described below in
  373. <A HREF="#data members as variables">Data Members as Variables</A>.)  Occasionally you'll see method names beginning or ending
  374. with an underscore or two.  This marking is a convention indicating
  375. that the methods are private to that class alone and sometimes to its
  376. closest acquaintances, its immediate subclasses.  But this distinction
  377. is not enforced by Perl itself.  It's up to the programmer to behave.</P>
  378. <P>There's no reason to limit methods to those that simply access data.
  379. Methods can do anything at all.  The key point is that they're invoked
  380. against an object or a class.  Let's say we'd like object methods that
  381. do more than fetch or set one particular field.</P>
  382. <PRE>
  383.     sub exclaim {
  384.         my $self = shift;
  385.         return sprintf "Hi, I'm %s, age %d, working with %s",
  386.             $self->{NAME}, $self->{AGE}, join(", ", @{$self->{PEERS}});
  387.     }</PRE>
  388. <P>Or maybe even one like this:</P>
  389. <PRE>
  390.     sub happy_birthday {
  391.         my $self = shift;
  392.         return ++$self->{AGE};
  393.     }</PRE>
  394. <P>Some might argue that one should go at these this way:</P>
  395. <PRE>
  396.     sub exclaim {
  397.         my $self = shift;
  398.         return sprintf "Hi, I'm %s, age %d, working with %s",
  399.             $self->name, $self->age, join(", ", $self->peers);
  400.     }</PRE>
  401. <PRE>
  402.     sub happy_birthday {
  403.         my $self = shift;
  404.         return $self->age( $self->age() + 1 );
  405.     }</PRE>
  406. <P>But since these methods are all executing in the class itself, this
  407. may not be critical.  There are tradeoffs to be made.  Using direct
  408. hash access is faster (about an order of magnitude faster, in fact), and
  409. it's more convenient when you want to interpolate in strings.  But using
  410. methods (the external interface) internally shields not just the users of
  411. your class but even you yourself from changes in your data representation.</P>
  412. <P>
  413. <HR>
  414. <H1><A NAME="class data">Class Data</A></H1>
  415. <P>What about ``class data'', data items common to each object in a class?
  416. What would you want that for?  Well, in your Person class, you might
  417. like to keep track of the total people alive.  How do you implement that?</P>
  418. <P>You <EM>could</EM> make it a global variable called $Person::Census.  But about
  419. only reason you'd do that would be if you <EM>wanted</EM> people to be able to
  420. get at your class data directly.  They could just say $Person::Census
  421. and play around with it.  Maybe this is ok in your design scheme.
  422. You might even conceivably want to make it an exported variable.  To be
  423. exportable, a variable must be a (package) global.  If this were a
  424. traditional module rather than an object-oriented one, you might do that.</P>
  425. <P>While this approach is expected in most traditional modules, it's
  426. generally considered rather poor form in most object modules.  In an
  427. object module, you should set up a protective veil to separate interface
  428. from implementation.  So provide a class method to access class data
  429. just as you provide object methods to access object data.</P>
  430. <P>So, you <EM>could</EM> still keep $Census as a package global and rely upon
  431. others to honor the contract of the module and therefore not play around
  432. with its implementation.  You could even be supertricky and make $Census a
  433. tied object as described in <A HREF="../../lib/Pod/perltie.html">the perltie manpage</A>, thereby intercepting all accesses.</P>
  434. <P>But more often than not, you just want to make your class data a
  435. file-scoped lexical.  To do so, simply put this at the top of the file:</P>
  436. <PRE>
  437.     my $Census = 0;</PRE>
  438. <P>Even though the scope of a <A HREF="../../lib/Pod/perlfunc.html#item_my"><CODE>my()</CODE></A> normally expires when the block in which
  439. it was declared is done (in this case the whole file being required or
  440. used), Perl's deep binding of lexical variables guarantees that the
  441. variable will not be deallocated, remaining accessible to functions
  442. declared within that scope.  This doesn't work with global variables
  443. given temporary values via local(), though.</P>
  444. <P>Irrespective of whether you leave $Census a package global or make
  445. it instead a file-scoped lexical, you should make these
  446. changes to your Person::new() constructor:</P>
  447. <PRE>
  448.     sub new {
  449.         my $proto = shift;
  450.         my $class = ref($proto) || $proto;
  451.         my $self  = {};
  452.         $Census++;
  453.         $self->{NAME}   = undef;
  454.         $self->{AGE}    = undef;
  455.         $self->{PEERS}  = [];
  456.         bless ($self, $class);
  457.         return $self;
  458.     }</PRE>
  459. <PRE>
  460.     sub population {
  461.         return $Census;
  462.     }</PRE>
  463. <P>Now that we've done this, we certainly do need a destructor so that
  464. when Person is destroyed, the $Census goes down.  Here's how
  465. this could be done:</P>
  466. <PRE>
  467.     sub DESTROY { --$Census }</PRE>
  468. <P>Notice how there's no memory to deallocate in the destructor?  That's
  469. something that Perl takes care of for you all by itself.</P>
  470. <P>
  471. <H2><A NAME="accessing class data">Accessing Class Data</A></H2>
  472. <P>It turns out that this is not really a good way to go about handling
  473. class data.  A good scalable rule is that <EM>you must never reference class
  474. data directly from an object method</EM>.  Otherwise you aren't building a
  475. scalable, inheritable class.  The object must be the rendezvous point
  476. for all operations, especially from an object method.  The globals
  477. (class data) would in some sense be in the ``wrong'' package in your
  478. derived classes.  In Perl, methods execute in the context of the class
  479. they were defined in, <EM>not</EM> that of the object that triggered them.
  480. Therefore, namespace visibility of package globals in methods is unrelated
  481. to inheritance.</P>
  482. <P>Got that?  Maybe not.  Ok, let's say that some other class ``borrowed''
  483. (well, inherited) the DESTROY method as it was defined above.  When those
  484. objects are destroyed, the original $Census variable will be altered,
  485. not the one in the new class's package namespace.  Perhaps this is what
  486. you want, but probably it isn't.</P>
  487. <P>Here's how to fix this.  We'll store a reference to the data in the
  488. value accessed by the hash key ``_CENSUS''.  Why the underscore?  Well,
  489. mostly because an initial underscore already conveys strong feelings
  490. of magicalness to a C programmer.  It's really just a mnemonic device
  491. to remind ourselves that this field is special and not to be used as
  492. a public data member in the same way that NAME, AGE, and PEERS are.
  493. (Because we've been developing this code under the strict pragma, prior
  494. to perl version 5.004 we'll have to quote the field name.)</P>
  495. <PRE>
  496.     sub new {
  497.         my $proto = shift;
  498.         my $class = ref($proto) || $proto;
  499.         my $self  = {};
  500.         $self->{NAME}     = undef;
  501.         $self->{AGE}      = undef;
  502.         $self->{PEERS}    = [];
  503.         # "private" data
  504.         $self->{"_CENSUS"} = \$Census;
  505.         bless ($self, $class);
  506.         ++ ${ $self->{"_CENSUS"} };
  507.         return $self;
  508.     }</PRE>
  509. <PRE>
  510.     sub population {
  511.         my $self = shift;
  512.         if (ref $self) {
  513.             return ${ $self->{"_CENSUS"} };
  514.         } else {
  515.             return $Census;
  516.         }
  517.     }</PRE>
  518. <PRE>
  519.     sub DESTROY {
  520.         my $self = shift;
  521.         -- ${ $self->{"_CENSUS"} };
  522.     }</PRE>
  523. <P>
  524. <H2><A NAME="debugging methods">Debugging Methods</A></H2>
  525. <P>It's common for a class to have a debugging mechanism.  For example,
  526. you might want to see when objects are created or destroyed.  To do that,
  527. add a debugging variable as a file-scoped lexical.  For this, we'll pull
  528. in the standard Carp module to emit our warnings and fatal messages.
  529. That way messages will come out with the caller's filename and
  530. line number instead of our own; if we wanted them to be from our own
  531. perspective, we'd just use <A HREF="../../lib/Pod/perlfunc.html#item_die"><CODE>die()</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_warn"><CODE>warn()</CODE></A> directly instead of <CODE>croak()</CODE>
  532. and <CODE>carp()</CODE> respectively.</P>
  533. <PRE>
  534.     use Carp;
  535.     my $Debugging = 0;</PRE>
  536. <P>Now add a new class method to access the variable.</P>
  537. <PRE>
  538.     sub debug {
  539.         my $class = shift;
  540.         if (ref $class)  { confess "Class method called as object method" }
  541.         unless (@_ == 1) { confess "usage: CLASSNAME->debug(level)" }
  542.         $Debugging = shift;
  543.     }</PRE>
  544. <P>Now fix up DESTROY to murmur a bit as the moribund object expires:</P>
  545. <PRE>
  546.     sub DESTROY {
  547.         my $self = shift;
  548.         if ($Debugging) { carp "Destroying $self " . $self->name }
  549.         -- ${ $self->{"_CENSUS"} };
  550.     }</PRE>
  551. <P>One could conceivably make a per-object debug state.  That
  552. way you could call both of these:</P>
  553. <PRE>
  554.     Person->debug(1);   # entire class
  555.     $him->debug(1);     # just this object</PRE>
  556. <P>To do so, we need our debugging method to be a ``bimodal'' one, one that
  557. works on both classes <EM>and</EM> objects.  Therefore, adjust the <CODE>debug()</CODE>
  558. and DESTROY methods as follows:</P>
  559. <PRE>
  560.     sub debug {
  561.         my $self = shift;
  562.         confess "usage: thing->debug(level)"    unless @_ == 1;
  563.         my $level = shift;
  564.         if (ref($self))  {
  565.             $self->{"_DEBUG"} = $level;         # just myself
  566.         } else {
  567.             $Debugging        = $level;         # whole class
  568.         }
  569.     }</PRE>
  570. <PRE>
  571.     sub DESTROY {
  572.         my $self = shift;
  573.         if ($Debugging || $self->{"_DEBUG"}) {
  574.             carp "Destroying $self " . $self->name;
  575.         }
  576.         -- ${ $self->{"_CENSUS"} };
  577.     }</PRE>
  578. <P>What happens if a derived class (which we'll call Employee) inherits
  579. methods from this Person base class?  Then <CODE>Employee->debug()</CODE>, when called
  580. as a class method, manipulates $Person::Debugging not $Employee::Debugging.</P>
  581. <P>
  582. <H2><A NAME="class destructors">Class Destructors</A></H2>
  583. <P>The object destructor handles the death of each distinct object.  But sometimes
  584. you want a bit of cleanup when the entire class is shut down, which
  585. currently only happens when the program exits.  To make such a
  586. <EM>class destructor</EM>, create a function in that class's package named
  587. END.  This works just like the END function in traditional modules,
  588. meaning that it gets called whenever your program exits unless it execs
  589. or dies of an uncaught signal.  For example,</P>
  590. <PRE>
  591.     sub END {
  592.         if ($Debugging) {
  593.             print "All persons are going away now.\n";
  594.         }
  595.     }</PRE>
  596. <P>When the program exits, all the class destructors (END functions) are
  597. be called in the opposite order that they were loaded in (LIFO order).</P>
  598. <P>
  599. <H2><A NAME="documenting the interface">Documenting the Interface</A></H2>
  600. <P>And there you have it: we've just shown you the <EM>implementation</EM> of this
  601. Person class.  Its <EM>interface</EM> would be its documentation.  Usually this
  602. means putting it in pod (``plain old documentation'') format right there
  603. in the same file.  In our Person example, we would place the following
  604. docs anywhere in the Person.pm file.  Even though it looks mostly like
  605. code, it's not.  It's embedded documentation such as would be used by
  606. the pod2man, pod2html, or pod2text programs.  The Perl compiler ignores
  607. pods entirely, just as the translators ignore code.  Here's an example of
  608. some pods describing the informal interface:</P>
  609. <PRE>
  610.     =head1 NAME</PRE>
  611. <PRE>
  612.     Person - class to implement people</PRE>
  613. <PRE>
  614.     =head1 SYNOPSIS</PRE>
  615. <PRE>
  616.      use Person;</PRE>
  617. <PRE>
  618.      #################
  619.      # class methods #
  620.      #################
  621.      $ob    = Person->new;
  622.      $count = Person->population;</PRE>
  623. <PRE>
  624.      #######################
  625.      # object data methods #
  626.      #######################</PRE>
  627. <PRE>
  628.      ### get versions ###
  629.          $who   = $ob->name;
  630.          $years = $ob->age;
  631.          @pals  = $ob->peers;</PRE>
  632. <PRE>
  633.      ### set versions ###
  634.          $ob->name("Jason");
  635.          $ob->age(23);
  636.          $ob->peers( "Norbert", "Rhys", "Phineas" );</PRE>
  637. <PRE>
  638.      ########################
  639.      # other object methods #
  640.      ########################</PRE>
  641. <PRE>
  642.      $phrase = $ob->exclaim;
  643.      $ob->happy_birthday;</PRE>
  644. <PRE>
  645.     =head1 DESCRIPTION</PRE>
  646. <PRE>
  647.     The Person class implements dah dee dah dee dah....</PRE>
  648. <P>That's all there is to the matter of interface versus implementation.
  649. A programmer who opens up the module and plays around with all the private
  650. little shiny bits that were safely locked up behind the interface contract
  651. has voided the warranty, and you shouldn't worry about their fate.</P>
  652. <P>
  653. <HR>
  654. <H1><A NAME="aggregation">Aggregation</A></H1>
  655. <P>Suppose you later want to change the class to implement better names.
  656. Perhaps you'd like to support both given names (called Christian names,
  657. irrespective of one's religion) and family names (called surnames), plus
  658. nicknames and titles.  If users of your Person class have been properly
  659. accessing it through its documented interface, then you can easily change
  660. the underlying implementation.  If they haven't, then they lose and
  661. it's their fault for breaking the contract and voiding their warranty.</P>
  662. <P>To do this, we'll make another class, this one called Fullname.  What's
  663. the Fullname class look like?  To answer that question, you have to
  664. first figure out how you want to use it.  How about we use it this way:</P>
  665. <PRE>
  666.     $him = Person->new();
  667.     $him->fullname->title("St");
  668.     $him->fullname->christian("Thomas");
  669.     $him->fullname->surname("Aquinas");
  670.     $him->fullname->nickname("Tommy");
  671.     printf "His normal name is %s\n", $him->name;
  672.     printf "But his real name is %s\n", $him->fullname->as_string;</PRE>
  673. <P>Ok.  To do this, we'll change Person::new() so that it supports
  674. a full name field this way:</P>
  675. <PRE>
  676.     sub new {
  677.         my $proto = shift;
  678.         my $class = ref($proto) || $proto;
  679.         my $self  = {};
  680.         $self->{FULLNAME} = Fullname->new();
  681.         $self->{AGE}      = undef;
  682.         $self->{PEERS}    = [];
  683.         $self->{"_CENSUS"} = \$Census;
  684.         bless ($self, $class);
  685.         ++ ${ $self->{"_CENSUS"} };
  686.         return $self;
  687.     }</PRE>
  688. <PRE>
  689.     sub fullname {
  690.         my $self = shift;
  691.         return $self->{FULLNAME};
  692.     }</PRE>
  693. <P>Then to support old code, define Person::name() this way:</P>
  694. <PRE>
  695.     sub name {
  696.         my $self = shift;
  697.         return $self->{FULLNAME}->nickname(@_)
  698.           ||   $self->{FULLNAME}->christian(@_);
  699.     }</PRE>
  700. <P>Here's the Fullname class.  We'll use the same technique
  701. of using a hash reference to hold data fields, and methods
  702. by the appropriate name to access them:</P>
  703. <PRE>
  704.     package Fullname;
  705.     use strict;</PRE>
  706. <PRE>
  707.     sub new {
  708.         my $proto = shift;
  709.         my $class = ref($proto) || $proto;
  710.         my $self  = {
  711.             TITLE       => undef,
  712.             CHRISTIAN   => undef,
  713.             SURNAME     => undef,
  714.             NICK        => undef,
  715.         };
  716.         bless ($self, $class);
  717.         return $self;
  718.     }</PRE>
  719. <PRE>
  720.     sub christian {
  721.         my $self = shift;
  722.         if (@_) { $self->{CHRISTIAN} = shift }
  723.         return $self->{CHRISTIAN};
  724.     }</PRE>
  725. <PRE>
  726.     sub surname {
  727.         my $self = shift;
  728.         if (@_) { $self->{SURNAME} = shift }
  729.         return $self->{SURNAME};
  730.     }</PRE>
  731. <PRE>
  732.     sub nickname {
  733.         my $self = shift;
  734.         if (@_) { $self->{NICK} = shift }
  735.         return $self->{NICK};
  736.     }</PRE>
  737. <PRE>
  738.     sub title {
  739.         my $self = shift;
  740.         if (@_) { $self->{TITLE} = shift }
  741.         return $self->{TITLE};
  742.     }</PRE>
  743. <PRE>
  744.     sub as_string {
  745.         my $self = shift;
  746.         my $name = join(" ", @$self{'CHRISTIAN', 'SURNAME'});
  747.         if ($self->{TITLE}) {
  748.             $name = $self->{TITLE} . " " . $name;
  749.         }
  750.         return $name;
  751.     }</PRE>
  752. <PRE>
  753.     1;</PRE>
  754. <P>Finally, here's the test program:</P>
  755. <PRE>
  756.     #!/usr/bin/perl -w
  757.     use strict;
  758.     use Person;
  759.     sub END { show_census() }</PRE>
  760. <PRE>
  761.     sub show_census ()  {
  762.         printf "Current population: %d\n", Person->population;
  763.     }</PRE>
  764. <PRE>
  765.     Person->debug(1);</PRE>
  766. <PRE>
  767.     show_census();</PRE>
  768. <PRE>
  769.     my $him = Person->new();</PRE>
  770. <PRE>
  771.     $him->fullname->christian("Thomas");
  772.     $him->fullname->surname("Aquinas");
  773.     $him->fullname->nickname("Tommy");
  774.     $him->fullname->title("St");
  775.     $him->age(1);</PRE>
  776. <PRE>
  777.     printf "%s is really %s.\n", $him->name, $him->fullname;
  778.     printf "%s's age: %d.\n", $him->name, $him->age;
  779.     $him->happy_birthday;
  780.     printf "%s's age: %d.\n", $him->name, $him->age;</PRE>
  781. <PRE>
  782.     show_census();</PRE>
  783. <P>
  784. <HR>
  785. <H1><A NAME="inheritance">Inheritance</A></H1>
  786. <P>Object-oriented programming systems all support some notion of
  787. inheritance.  Inheritance means allowing one class to piggy-back on
  788. top of another one so you don't have to write the same code again and
  789. again.  It's about software reuse, and therefore related to Laziness,
  790. the principal virtue of a programmer.  (The import/export mechanisms in
  791. traditional modules are also a form of code reuse, but a simpler one than
  792. the true inheritance that you find in object modules.)</P>
  793. <P>Sometimes the syntax of inheritance is built into the core of the
  794. language, and sometimes it's not.  Perl has no special syntax for
  795. specifying the class (or classes) to inherit from.  Instead, it's all
  796. strictly in the semantics.  Each package can have a variable called @ISA,
  797. which governs (method) inheritance.  If you try to call a method on an
  798. object or class, and that method is not found in that object's package,
  799. Perl then looks to @ISA for other packages to go looking through in
  800. search of the missing method.</P>
  801. <P>Like the special per-package variables recognized by Exporter (such as
  802. @EXPORT, @EXPORT_OK, @EXPORT_FAIL, %EXPORT_TAGS, and $VERSION), the @ISA
  803. array <EM>must</EM> be a package-scoped global and not a file-scoped lexical
  804. created via my().  Most classes have just one item in their @ISA array.
  805. In this case, we have what's called ``single inheritance'', or SI for short.</P>
  806. <P>Consider this class:</P>
  807. <PRE>
  808.     package Employee;
  809.     use Person;
  810.     @ISA = ("Person");
  811.     1;</PRE>
  812. <P>Not a lot to it, eh?  All it's doing so far is loading in another
  813. class and stating that this one will inherit methods from that
  814. other class if need be.  We have given it none of its own methods.
  815. We rely upon an Employee to behave just like a Person.</P>
  816. <P>Setting up an empty class like this is called the ``empty subclass test'';
  817. that is, making a derived class that does nothing but inherit from a
  818. base class.  If the original base class has been designed properly,
  819. then the new derived class can be used as a drop-in replacement for the
  820. old one.  This means you should be able to write a program like this:</P>
  821. <PRE>
  822.     use Employee;
  823.     my $empl = Employee->new();
  824.     $empl->name("Jason");
  825.     $empl->age(23);
  826.     printf "%s is age %d.\n", $empl->name, $empl->age;</PRE>
  827. <P>By proper design, we mean always using the two-argument form of bless(),
  828. avoiding direct access of global data, and not exporting anything.  If you
  829. look back at the Person::new() function we defined above, we were careful
  830. to do that.  There's a bit of package data used in the constructor,
  831. but the reference to this is stored on the object itself and all other
  832. methods access package data via that reference, so we should be ok.</P>
  833. <P>What do we mean by the Person::new() function -- isn't that actually
  834. a method?  Well, in principle, yes.  A method is just a function that
  835. expects as its first argument a class name (package) or object
  836. (blessed reference).   Person::new() is the function that both the
  837. <CODE>Person->new()</CODE> method and the <CODE>Employee->new()</CODE> method end
  838. up calling.  Understand that while a method call looks a lot like a
  839. function call, they aren't really quite the same, and if you treat them
  840. as the same, you'll very soon be left with nothing but broken programs.
  841. First, the actual underlying calling conventions are different: method
  842. calls get an extra argument.  Second, function calls don't do inheritance,
  843. but methods do.</P>
  844. <PRE>
  845.         Method Call             Resulting Function Call
  846.         -----------             ------------------------
  847.         Person->new()           Person::new("Person")
  848.         Employee->new()         Person::new("Employee")</PRE>
  849. <P>So don't use function calls when you mean to call a method.</P>
  850. <P>If an employee is just a Person, that's not all too very interesting.
  851. So let's add some other methods.  We'll give our employee
  852. data fields to access their salary, their employee ID, and their
  853. start date.</P>
  854. <P>If you're getting a little tired of creating all these nearly identical
  855. methods just to get at the object's data, do not despair.  Later,
  856. we'll describe several different convenience mechanisms for shortening
  857. this up.  Meanwhile, here's the straight-forward way:</P>
  858. <PRE>
  859.     sub salary {
  860.         my $self = shift;
  861.         if (@_) { $self->{SALARY} = shift }
  862.         return $self->{SALARY};
  863.     }</PRE>
  864. <PRE>
  865.     sub id_number {
  866.         my $self = shift;
  867.         if (@_) { $self->{ID} = shift }
  868.         return $self->{ID};
  869.     }</PRE>
  870. <PRE>
  871.     sub start_date {
  872.         my $self = shift;
  873.         if (@_) { $self->{START_DATE} = shift }
  874.         return $self->{START_DATE};
  875.     }</PRE>
  876. <P>
  877. <H2><A NAME="overridden methods">Overridden Methods</A></H2>
  878. <P>What happens when both a derived class and its base class have the same
  879. method defined?  Well, then you get the derived class's version of that
  880. method.  For example, let's say that we want the <CODE>peers()</CODE> method called on
  881. an employee to act a bit differently.  Instead of just returning the list
  882. of peer names, let's return slightly different strings.  So doing this:</P>
  883. <PRE>
  884.     $empl->peers("Peter", "Paul", "Mary");
  885.     printf "His peers are: %s\n", join(", ", $empl->peers);</PRE>
  886. <P>will produce:</P>
  887. <PRE>
  888.     His peers are: PEON=PETER, PEON=PAUL, PEON=MARY</PRE>
  889. <P>To do this, merely add this definition into the Employee.pm file:</P>
  890. <PRE>
  891.     sub peers {
  892.         my $self = shift;
  893.         if (@_) { @{ $self->{PEERS} } = @_ }
  894.         return map { "PEON=\U$_" } @{ $self->{PEERS} };
  895.     }</PRE>
  896. <P>There, we've just demonstrated the high-falutin' concept known in certain
  897. circles as <EM>polymorphism</EM>.  We've taken on the form and behaviour of
  898. an existing object, and then we've altered it to suit our own purposes.
  899. This is a form of Laziness.  (Getting polymorphed is also what happens
  900. when the wizard decides you'd look better as a frog.)</P>
  901. <P>Every now and then you'll want to have a method call trigger both its
  902. derived class (also known as ``subclass'') version as well as its base class
  903. (also known as ``superclass'') version.  In practice, constructors and
  904. destructors are likely to want to do this, and it probably also makes
  905. sense in the <CODE>debug()</CODE> method we showed previously.</P>
  906. <P>To do this, add this to Employee.pm:</P>
  907. <PRE>
  908.     use Carp;
  909.     my $Debugging = 0;</PRE>
  910. <PRE>
  911.     sub debug {
  912.         my $self = shift;
  913.         confess "usage: thing->debug(level)"    unless @_ == 1;
  914.         my $level = shift;
  915.         if (ref($self))  {
  916.             $self->{"_DEBUG"} = $level;
  917.         } else {
  918.             $Debugging = $level;            # whole class
  919.         }
  920.         Person::debug($self, $Debugging);   # don't really do this
  921.     }</PRE>
  922. <P>As you see, we turn around and call the Person package's <CODE>debug()</CODE> function.
  923. But this is far too fragile for good design.  What if Person doesn't
  924. have a <CODE>debug()</CODE> function, but is inheriting <EM>its</EM> <CODE>debug()</CODE> method
  925. from elsewhere?  It would have been slightly better to say</P>
  926. <PRE>
  927.     Person->debug($Debugging);</PRE>
  928. <P>But even that's got too much hard-coded.  It's somewhat better to say</P>
  929. <PRE>
  930.     $self->Person::debug($Debugging);</PRE>
  931. <P>Which is a funny way to say to start looking for a <CODE>debug()</CODE> method up
  932. in Person.  This strategy is more often seen on overridden object methods
  933. than on overridden class methods.</P>
  934. <P>There is still something a bit off here.  We've hard-coded our
  935. superclass's name.  This in particular is bad if you change which classes
  936. you inherit from, or add others.  Fortunately, the pseudoclass SUPER
  937. comes to the rescue here.</P>
  938. <PRE>
  939.     $self->SUPER::debug($Debugging);</PRE>
  940. <P>This way it starts looking in my class's @ISA.  This only makes sense
  941. from <EM>within</EM> a method call, though.  Don't try to access anything
  942. in SUPER:: from anywhere else, because it doesn't exist outside
  943. an overridden method call.</P>
  944. <P>Things are getting a bit complicated here.  Have we done anything
  945. we shouldn't?  As before, one way to test whether we're designing
  946. a decent class is via the empty subclass test.  Since we already have
  947. an Employee class that we're trying to check, we'd better get a new
  948. empty subclass that can derive from Employee.  Here's one:</P>
  949. <PRE>
  950.     package Boss;
  951.     use Employee;        # :-)
  952.     @ISA = qw(Employee);</PRE>
  953. <P>And here's the test program:</P>
  954. <PRE>
  955.     #!/usr/bin/perl -w
  956.     use strict;
  957.     use Boss;
  958.     Boss->debug(1);</PRE>
  959. <PRE>
  960.     my $boss = Boss->new();</PRE>
  961. <PRE>
  962.     $boss->fullname->title("Don");
  963.     $boss->fullname->surname("Pichon Alvarez");
  964.     $boss->fullname->christian("Federico Jesus");
  965.     $boss->fullname->nickname("Fred");</PRE>
  966. <PRE>
  967.     $boss->age(47);
  968.     $boss->peers("Frank", "Felipe", "Faust");</PRE>
  969. <PRE>
  970.     printf "%s is age %d.\n", $boss->fullname, $boss->age;
  971.     printf "His peers are: %s\n", join(", ", $boss->peers);</PRE>
  972. <P>Running it, we see that we're still ok.  If you'd like to dump out your
  973. object in a nice format, somewhat like the way the 'x' command works in
  974. the debugger, you could use the Data::Dumper module from CPAN this way:</P>
  975. <PRE>
  976.     use Data::Dumper;
  977.     print "Here's the boss:\n";
  978.     print Dumper($boss);</PRE>
  979. <P>Which shows us something like this:</P>
  980. <PRE>
  981.     Here's the boss:
  982.     $VAR1 = bless( {
  983.          _CENSUS => \1,
  984.          FULLNAME => bless( {
  985.                               TITLE => 'Don',
  986.                               SURNAME => 'Pichon Alvarez',
  987.                               NICK => 'Fred',
  988.                               CHRISTIAN => 'Federico Jesus'
  989.                             }, 'Fullname' ),
  990.          AGE => 47,
  991.          PEERS => [
  992.                     'Frank',
  993.                     'Felipe',
  994.                     'Faust'
  995.                   ]
  996.        }, 'Boss' );</PRE>
  997. <P>Hm.... something's missing there.  What about the salary, start date,
  998. and ID fields?  Well, we never set them to anything, even undef, so they
  999. don't show up in the hash's keys.  The Employee class has no <CODE>new()</CODE> method
  1000. of its own, and the <CODE>new()</CODE> method in Person doesn't know about Employees.
  1001. (Nor should it: proper OO design dictates that a subclass be allowed to
  1002. know about its immediate superclass, but never vice-versa.)  So let's
  1003. fix up Employee::new() this way:</P>
  1004. <PRE>
  1005.     sub new {
  1006.         my $proto = shift;
  1007.         my $class = ref($proto) || $proto;
  1008.         my $self  = $class->SUPER::new();
  1009.         $self->{SALARY}        = undef;
  1010.         $self->{ID}            = undef;
  1011.         $self->{START_DATE}    = undef;
  1012.         bless ($self, $class);          # reconsecrate
  1013.         return $self;
  1014.     }</PRE>
  1015. <P>Now if you dump out an Employee or Boss object, you'll find
  1016. that new fields show up there now.</P>
  1017. <P>
  1018. <H2><A NAME="multiple inheritance">Multiple Inheritance</A></H2>
  1019. <P>Ok, at the risk of confusing beginners and annoying OO gurus, it's
  1020. time to confess that Perl's object system includes that controversial
  1021. notion known as multiple inheritance, or MI for short.  All this means
  1022. is that rather than having just one parent class who in turn might
  1023. itself have a parent class, etc., that you can directly inherit from
  1024. two or more parents.  It's true that some uses of MI can get you into
  1025. trouble, although hopefully not quite so much trouble with Perl as with
  1026. dubiously-OO languages like C++.</P>
  1027. <P>The way it works is actually pretty simple: just put more than one package
  1028. name in your @ISA array.  When it comes time for Perl to go finding
  1029. methods for your object, it looks at each of these packages in order.
  1030. Well, kinda.  It's actually a fully recursive, depth-first order.
  1031. Consider a bunch of @ISA arrays like this:</P>
  1032. <PRE>
  1033.     @First::ISA    = qw( Alpha );
  1034.     @Second::ISA   = qw( Beta );
  1035.     @Third::ISA    = qw( First Second );</PRE>
  1036. <P>If you have an object of class Third:</P>
  1037. <PRE>
  1038.     my $ob = Third->new();
  1039.     $ob->spin();</PRE>
  1040. <P>How do we find a <CODE>spin()</CODE> method (or a <CODE>new()</CODE> method for that matter)?
  1041. Because the search is depth-first, classes will be looked up
  1042. in the following order: Third, First, Alpha, Second, and Beta.</P>
  1043. <P>In practice, few class modules have been seen that actually
  1044. make use of MI.  One nearly always chooses simple containership of
  1045. one class within another over MI.  That's why our Person
  1046. object <EM>contained</EM> a Fullname object.  That doesn't mean
  1047. it <EM>was</EM> one.</P>
  1048. <P>However, there is one particular area where MI in Perl is rampant:
  1049. borrowing another class's class methods.  This is rather common,
  1050. especially with some bundled ``objectless'' classes,
  1051. like Exporter, DynaLoader, AutoLoader, and SelfLoader.  These classes
  1052. do not provide constructors; they exist only so you may inherit their
  1053. class methods.  (It's not entirely clear why inheritance was done
  1054. here rather than traditional module importation.)</P>
  1055. <P>For example, here is the POSIX module's @ISA:</P>
  1056. <PRE>
  1057.     package POSIX;
  1058.     @ISA = qw(Exporter DynaLoader);</PRE>
  1059. <P>The POSIX module isn't really an object module, but then,
  1060. neither are Exporter or DynaLoader.  They're just lending their
  1061. classes' behaviours to POSIX.</P>
  1062. <P>Why don't people use MI for object methods much?  One reason is that
  1063. it can have complicated side-effects.  For one thing, your inheritance
  1064. graph (no longer a tree) might converge back to the same base class.
  1065. Although Perl guards against recursive inheritance, merely having parents
  1066. who are related to each other via a common ancestor, incestuous though
  1067. it sounds, is not forbidden.  What if in our Third class shown above we
  1068. wanted its <CODE>new()</CODE> method to also call both overridden constructors in its
  1069. two parent classes?  The SUPER notation would only find the first one.
  1070. Also, what about if the Alpha and Beta classes both had a common ancestor,
  1071. like Nought?  If you kept climbing up the inheritance tree calling
  1072. overridden methods, you'd end up calling Nought::new() twice,
  1073. which might well be a bad idea.</P>
  1074. <P>
  1075. <H2><A NAME="universal: the root of all objects">UNIVERSAL: The Root of All Objects</A></H2>
  1076. <P>Wouldn't it be convenient if all objects were rooted at some ultimate
  1077. base class?  That way you could give every object common methods without
  1078. having to go and add it to each and every @ISA.  Well, it turns out that
  1079. you can.  You don't see it, but Perl tacitly and irrevocably assumes
  1080. that there's an extra element at the end of @ISA: the class UNIVERSAL.
  1081. In version 5.003, there were no predefined methods there, but you could put
  1082. whatever you felt like into it.</P>
  1083. <P>However, as of version 5.004 (or some subversive releases, like 5.003_08),
  1084. UNIVERSAL has some methods in it already.  These are builtin to your Perl
  1085. binary, so they don't take any extra time to load.  Predefined methods
  1086. include isa(), can(), and VERSION().  <CODE>isa()</CODE> tells you whether an object or
  1087. class ``is'' another one without having to traverse the hierarchy yourself:</P>
  1088. <PRE>
  1089.    $has_io = $fd->isa("IO::Handle");
  1090.    $itza_handle = IO::Socket->isa("IO::Handle");</PRE>
  1091. <P>The <CODE>can()</CODE> method, called against that object or class, reports back
  1092. whether its string argument is a callable method name in that class.
  1093. In fact, it gives you back a function reference to that method:</P>
  1094. <PRE>
  1095.    $his_print_method = $obj->can('as_string');</PRE>
  1096. <P>Finally, the VERSION method checks whether the class (or the object's
  1097. class) has a package global called $VERSION that's high enough, as in:</P>
  1098. <PRE>
  1099.     Some_Module->VERSION(3.0);
  1100.     $his_vers = $ob->VERSION();</PRE>
  1101. <P>However, we don't usually call VERSION ourselves.  (Remember that an all
  1102. uppercase function name is a Perl convention that indicates that the
  1103. function will be automatically used by Perl in some way.)  In this case,
  1104. it happens when you say</P>
  1105. <PRE>
  1106.     use Some_Module 3.0;</PRE>
  1107. <P>If you wanted to add version checking to your Person class explained
  1108. above, just add this to Person.pm:</P>
  1109. <PRE>
  1110.     our $VERSION = '1.1';</PRE>
  1111. <P>and then in Employee.pm could you can say</P>
  1112. <PRE>
  1113.     use Employee 1.1;</PRE>
  1114. <P>And it would make sure that you have at least that version number or
  1115. higher available.   This is not the same as loading in that exact version
  1116. number.  No mechanism currently exists for concurrent installation of
  1117. multiple versions of a module.  Lamentably.</P>
  1118. <P>
  1119. <HR>
  1120. <H1><A NAME="alternate object representations">Alternate Object Representations</A></H1>
  1121. <P>Nothing requires objects to be implemented as hash references.  An object
  1122. can be any sort of reference so long as its referent has been suitably
  1123. blessed.  That means scalar, array, and code references are also fair
  1124. game.</P>
  1125. <P>A scalar would work if the object has only one datum to hold.  An array
  1126. would work for most cases, but makes inheritance a bit dodgy because
  1127. you have to invent new indices for the derived classes.</P>
  1128. <P>
  1129. <H2><A NAME="arrays as objects">Arrays as Objects</A></H2>
  1130. <P>If the user of your class honors the contract and sticks to the advertised
  1131. interface, then you can change its underlying interface if you feel
  1132. like it.  Here's another implementation that conforms to the same
  1133. interface specification.  This time we'll use an array reference
  1134. instead of a hash reference to represent the object.</P>
  1135. <PRE>
  1136.     package Person;
  1137.     use strict;</PRE>
  1138. <PRE>
  1139.     my($NAME, $AGE, $PEERS) = ( 0 .. 2 );</PRE>
  1140. <PRE>
  1141.     ############################################
  1142.     ## the object constructor (array version) ##
  1143.     ############################################
  1144.     sub new {
  1145.         my $self = [];
  1146.         $self->[$NAME]   = undef;  # this is unnecessary
  1147.         $self->[$AGE]    = undef;  # as is this
  1148.         $self->[$PEERS]  = [];     # but this isn't, really
  1149.         bless($self);
  1150.         return $self;
  1151.     }</PRE>
  1152. <PRE>
  1153.     sub name {
  1154.         my $self = shift;
  1155.         if (@_) { $self->[$NAME] = shift }
  1156.         return $self->[$NAME];
  1157.     }</PRE>
  1158. <PRE>
  1159.     sub age {
  1160.         my $self = shift;
  1161.         if (@_) { $self->[$AGE] = shift }
  1162.         return $self->[$AGE];
  1163.     }</PRE>
  1164. <PRE>
  1165.     sub peers {
  1166.         my $self = shift;
  1167.         if (@_) { @{ $self->[$PEERS] } = @_ }
  1168.         return @{ $self->[$PEERS] };
  1169.     }</PRE>
  1170. <PRE>
  1171.     1;  # so the require or use succeeds</PRE>
  1172. <P>You might guess that the array access would be a lot faster than the
  1173. hash access, but they're actually comparable.  The array is a <EM>little</EM>
  1174. bit faster, but not more than ten or fifteen percent, even when you
  1175. replace the variables above like $AGE with literal numbers, like 1.
  1176. A bigger difference between the two approaches can be found in memory use.
  1177. A hash representation takes up more memory than an array representation
  1178. because you have to allocate memory for the keys as well as for the values.
  1179. However, it really isn't that bad, especially since as of version 5.004,
  1180. memory is only allocated once for a given hash key, no matter how many
  1181. hashes have that key.  It's expected that sometime in the future, even
  1182. these differences will fade into obscurity as more efficient underlying
  1183. representations are devised.</P>
  1184. <P>Still, the tiny edge in speed (and somewhat larger one in memory)
  1185. is enough to make some programmers choose an array representation
  1186. for simple classes.  There's still a little problem with
  1187. scalability, though, because later in life when you feel
  1188. like creating subclasses, you'll find that hashes just work
  1189. out better.</P>
  1190. <P>
  1191. <H2><A NAME="closures as objects">Closures as Objects</A></H2>
  1192. <P>Using a code reference to represent an object offers some fascinating
  1193. possibilities.  We can create a new anonymous function (closure) who
  1194. alone in all the world can see the object's data.  This is because we
  1195. put the data into an anonymous hash that's lexically visible only to
  1196. the closure we create, bless, and return as the object.  This object's
  1197. methods turn around and call the closure as a regular subroutine call,
  1198. passing it the field we want to affect.  (Yes,
  1199. the double-function call is slow, but if you wanted fast, you wouldn't
  1200. be using objects at all, eh? :-)</P>
  1201. <P>Use would be similar to before:</P>
  1202. <PRE>
  1203.     use Person;
  1204.     $him = Person->new();
  1205.     $him->name("Jason");
  1206.     $him->age(23);
  1207.     $him->peers( [ "Norbert", "Rhys", "Phineas" ] );
  1208.     printf "%s is %d years old.\n", $him->name, $him->age;
  1209.     print "His peers are: ", join(", ", @{$him->peers}), "\n";</PRE>
  1210. <P>but the implementation would be radically, perhaps even sublimely
  1211. different:</P>
  1212. <PRE>
  1213.     package Person;</PRE>
  1214. <PRE>
  1215.     sub new {
  1216.          my $that  = shift;
  1217.          my $class = ref($that) || $that;
  1218.          my $self = {
  1219.             NAME  => undef,
  1220.             AGE   => undef,
  1221.             PEERS => [],
  1222.          };
  1223.          my $closure = sub {
  1224.             my $field = shift;
  1225.             if (@_) { $self->{$field} = shift }
  1226.             return    $self->{$field};
  1227.         };
  1228.         bless($closure, $class);
  1229.         return $closure;
  1230.     }</PRE>
  1231. <PRE>
  1232.     sub name   { &{ $_[0] }("NAME",  @_[ 1 .. $#_ ] ) }
  1233.     sub age    { &{ $_[0] }("AGE",   @_[ 1 .. $#_ ] ) }
  1234.     sub peers  { &{ $_[0] }("PEERS", @_[ 1 .. $#_ ] ) }</PRE>
  1235. <PRE>
  1236.     1;</PRE>
  1237. <P>Because this object is hidden behind a code reference, it's probably a bit
  1238. mysterious to those whose background is more firmly rooted in standard
  1239. procedural or object-based programming languages than in functional
  1240. programming languages whence closures derive.  The object
  1241. created and returned by the <CODE>new()</CODE> method is itself not a data reference
  1242. as we've seen before.  It's an anonymous code reference that has within
  1243. it access to a specific version (lexical binding and instantiation)
  1244. of the object's data, which are stored in the private variable $self.
  1245. Although this is the same function each time, it contains a different
  1246. version of $self.</P>
  1247. <P>When a method like <CODE>$him->name("Jason")</CODE> is called, its implicit
  1248. zeroth argument is the invoking object--just as it is with all method
  1249. calls.  But in this case, it's our code reference (something like a
  1250. function pointer in C++, but with deep binding of lexical variables).
  1251. There's not a lot to be done with a code reference beyond calling it, so
  1252. that's just what we do when we say <CODE>&{$_[0]}</CODE>.  This is just a regular
  1253. function call, not a method call.  The initial argument is the string
  1254. ``NAME'', and any remaining arguments are whatever had been passed to the
  1255. method itself.</P>
  1256. <P>Once we're executing inside the closure that had been created in new(),
  1257. the $self hash reference suddenly becomes visible.  The closure grabs
  1258. its first argument (``NAME'' in this case because that's what the <CODE>name()</CODE>
  1259. method passed it), and uses that string to subscript into the private
  1260. hash hidden in its unique version of $self.</P>
  1261. <P>Nothing under the sun will allow anyone outside the executing method to
  1262. be able to get at this hidden data.  Well, nearly nothing.  You <EM>could</EM>
  1263. single step through the program using the debugger and find out the
  1264. pieces while you're in the method, but everyone else is out of luck.</P>
  1265. <P>There, if that doesn't excite the Scheme folks, then I just don't know
  1266. what will.  Translation of this technique into C++, Java, or any other
  1267. braindead-static language is left as a futile exercise for aficionados
  1268. of those camps.</P>
  1269. <P>You could even add a bit of nosiness via the <A HREF="../../lib/Pod/perlfunc.html#item_caller"><CODE>caller()</CODE></A> function and
  1270. make the closure refuse to operate unless called via its own package.
  1271. This would no doubt satisfy certain fastidious concerns of programming
  1272. police and related puritans.</P>
  1273. <P>If you were wondering when Hubris, the third principle virtue of a
  1274. programmer, would come into play, here you have it. (More seriously,
  1275. Hubris is just the pride in craftsmanship that comes from having written
  1276. a sound bit of well-designed code.)</P>
  1277. <P>
  1278. <HR>
  1279. <H1><A NAME="autoload: proxy methods">AUTOLOAD: Proxy Methods</A></H1>
  1280. <P>Autoloading is a way to intercept calls to undefined methods.  An autoload
  1281. routine may choose to create a new function on the fly, either loaded
  1282. from disk or perhaps just eval()ed right there.  This define-on-the-fly
  1283. strategy is why it's called autoloading.</P>
  1284. <P>But that's only one possible approach.  Another one is to just
  1285. have the autoloaded method itself directly provide the
  1286. requested service.  When used in this way, you may think
  1287. of autoloaded methods as ``proxy'' methods.</P>
  1288. <P>When Perl tries to call an undefined function in a particular package
  1289. and that function is not defined, it looks for a function in
  1290. that same package called AUTOLOAD.  If one exists, it's called
  1291. with the same arguments as the original function would have had.
  1292. The fully-qualified name of the function is stored in that package's
  1293. global variable $AUTOLOAD.  Once called, the function can do anything
  1294. it would like, including defining a new function by the right name, and
  1295. then doing a really fancy kind of <A HREF="../../lib/Pod/perlfunc.html#item_goto"><CODE>goto</CODE></A> right to it, erasing itself
  1296. from the call stack.</P>
  1297. <P>What does this have to do with objects?  After all, we keep talking about
  1298. functions, not methods.  Well, since a method is just a function with
  1299. an extra argument and some fancier semantics about where it's found,
  1300. we can use autoloading for methods, too.  Perl doesn't start looking
  1301. for an AUTOLOAD method until it has exhausted the recursive hunt up
  1302. through @ISA, though.  Some programmers have even been known to define
  1303. a UNIVERSAL::AUTOLOAD method to trap unresolved method calls to any
  1304. kind of object.</P>
  1305. <P>
  1306. <H2><A NAME="autoloaded data methods">Autoloaded Data Methods</A></H2>
  1307. <P>You probably began to get a little suspicious about the duplicated
  1308. code way back earlier when we first showed you the Person class, and
  1309. then later the Employee class.  Each method used to access the
  1310. hash fields looked virtually identical.  This should have tickled
  1311. that great programming virtue, Impatience, but for the time,
  1312. we let Laziness win out, and so did nothing.  Proxy methods can cure
  1313. this.</P>
  1314. <P>Instead of writing a new function every time we want a new data field,
  1315. we'll use the autoload mechanism to generate (actually, mimic) methods on
  1316. the fly.  To verify that we're accessing a valid member, we will check
  1317. against an <CODE>_permitted</CODE> (pronounced ``under-permitted'') field, which
  1318. is a reference to a file-scoped lexical (like a C file static) hash of permitted fields in this record
  1319. called %fields.  Why the underscore?  For the same reason as the _CENSUS
  1320. field we once used: as a marker that means ``for internal use only''.</P>
  1321. <P>Here's what the module initialization code and class
  1322. constructor will look like when taking this approach:</P>
  1323. <PRE>
  1324.     package Person;
  1325.     use Carp;
  1326.     our $AUTOLOAD;  # it's a package global</PRE>
  1327. <PRE>
  1328.     my %fields = (
  1329.         name        => undef,
  1330.         age         => undef,
  1331.         peers       => undef,
  1332.     );</PRE>
  1333. <PRE>
  1334.     sub new {
  1335.         my $that  = shift;
  1336.         my $class = ref($that) || $that;
  1337.         my $self  = {
  1338.             _permitted => \%fields,
  1339.             %fields,
  1340.         };
  1341.         bless $self, $class;
  1342.         return $self;
  1343.     }</PRE>
  1344. <P>If we wanted our record to have default values, we could fill those in
  1345. where current we have <A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A> in the %fields hash.</P>
  1346. <P>Notice how we saved a reference to our class data on the object itself?
  1347. Remember that it's important to access class data through the object
  1348. itself instead of having any method reference %fields directly, or else
  1349. you won't have a decent inheritance.</P>
  1350. <P>The real magic, though, is going to reside in our proxy method, which
  1351. will handle all calls to undefined methods for objects of class Person
  1352. (or subclasses of Person).  It has to be called AUTOLOAD.  Again, it's
  1353. all caps because it's called for us implicitly by Perl itself, not by
  1354. a user directly.</P>
  1355. <PRE>
  1356.     sub AUTOLOAD {
  1357.         my $self = shift;
  1358.         my $type = ref($self)
  1359.                     or croak "$self is not an object";</PRE>
  1360. <PRE>
  1361.         my $name = $AUTOLOAD;
  1362.         $name =~ s/.*://;   # strip fully-qualified portion</PRE>
  1363. <PRE>
  1364.         unless (exists $self->{_permitted}->{$name} ) {
  1365.             croak "Can't access `$name' field in class $type";
  1366.         }</PRE>
  1367. <PRE>
  1368.         if (@_) {
  1369.             return $self->{$name} = shift;
  1370.         } else {
  1371.             return $self->{$name};
  1372.         }
  1373.     }</PRE>
  1374. <P>Pretty nifty, eh?  All we have to do to add new data fields
  1375. is modify %fields.  No new functions need be written.</P>
  1376. <P>I could have avoided the <CODE>_permitted</CODE> field entirely, but I
  1377. wanted to demonstrate how to store a reference to class data on the
  1378. object so you wouldn't have to access that class data
  1379. directly from an object method.</P>
  1380. <P>
  1381. <H2><A NAME="inherited autoloaded data methods">Inherited Autoloaded Data Methods</A></H2>
  1382. <P>But what about inheritance?  Can we define our Employee
  1383. class similarly?  Yes, so long as we're careful enough.</P>
  1384. <P>Here's how to be careful:</P>
  1385. <PRE>
  1386.     package Employee;
  1387.     use Person;
  1388.     use strict;
  1389.     our @ISA = qw(Person);</PRE>
  1390. <PRE>
  1391.     my %fields = (
  1392.         id          => undef,
  1393.         salary      => undef,
  1394.     );</PRE>
  1395. <PRE>
  1396.     sub new {
  1397.         my $that  = shift;
  1398.         my $class = ref($that) || $that;
  1399.         my $self = bless $that->SUPER::new(), $class;
  1400.         my($element);
  1401.         foreach $element (keys %fields) {
  1402.             $self->{_permitted}->{$element} = $fields{$element};
  1403.         }
  1404.         @{$self}{keys %fields} = values %fields;
  1405.         return $self;
  1406.     }</PRE>
  1407. <P>Once we've done this, we don't even need to have an
  1408. AUTOLOAD function in the Employee package, because
  1409. we'll grab Person's version of that via inheritance,
  1410. and it will all work out just fine.</P>
  1411. <P>
  1412. <HR>
  1413. <H1><A NAME="metaclassical tools">Metaclassical Tools</A></H1>
  1414. <P>Even though proxy methods can provide a more convenient approach to making
  1415. more struct-like classes than tediously coding up data methods as
  1416. functions, it still leaves a bit to be desired.  For one thing, it means
  1417. you have to handle bogus calls that you don't mean to trap via your proxy.
  1418. It also means you have to be quite careful when dealing with inheritance,
  1419. as detailed above.</P>
  1420. <P>Perl programmers have responded to this by creating several different
  1421. class construction classes.  These metaclasses are classes
  1422. that create other classes.  A couple worth looking at are
  1423. Class::Struct and Alias.  These and other related metaclasses can be
  1424. found in the modules directory on CPAN.</P>
  1425. <P>
  1426. <H2><A NAME="class::struct">Class::Struct</A></H2>
  1427. <P>One of the older ones is Class::Struct.  In fact, its syntax and
  1428. interface were sketched out long before perl5 even solidified into a
  1429. real thing.  What it does is provide you a way to ``declare'' a class
  1430. as having objects whose fields are of a specific type.  The function
  1431. that does this is called, not surprisingly enough, struct().  Because
  1432. structures or records are not base types in Perl, each time you want to
  1433. create a class to provide a record-like data object, you yourself have
  1434. to define a <CODE>new()</CODE> method, plus separate data-access methods for each of
  1435. that record's fields.  You'll quickly become bored with this process.
  1436. The Class::Struct::struct() function alleviates this tedium.</P>
  1437. <P>Here's a simple example of using it:</P>
  1438. <PRE>
  1439.     use Class::Struct qw(struct);
  1440.     use Jobbie;  # user-defined; see below</PRE>
  1441. <PRE>
  1442.     struct 'Fred' => {
  1443.         one        => '$',
  1444.         many       => '@',
  1445.         profession => Jobbie,  # calls Jobbie->new()
  1446.     };</PRE>
  1447. <PRE>
  1448.     $ob = Fred->new;
  1449.     $ob->one("hmmmm");</PRE>
  1450. <PRE>
  1451.     $ob->many(0, "here");
  1452.     $ob->many(1, "you");
  1453.     $ob->many(2, "go");
  1454.     print "Just set: ", $ob->many(2), "\n";</PRE>
  1455. <PRE>
  1456.     $ob->profession->salary(10_000);</PRE>
  1457. <P>You can declare types in the struct to be basic Perl types, or
  1458. user-defined types (classes).  User types will be initialized by calling
  1459. that class's <CODE>new()</CODE> method.</P>
  1460. <P>Here's a real-world example of using struct generation.  Let's say you
  1461. wanted to override Perl's idea of <A HREF="../../lib/Pod/perlfunc.html#item_gethostbyname"><CODE>gethostbyname()</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_gethostbyaddr"><CODE>gethostbyaddr()</CODE></A> so
  1462. that they would return objects that acted like C structures.  We don't
  1463. care about high-falutin' OO gunk.  All we want is for these objects to
  1464. act like structs in the C sense.</P>
  1465. <PRE>
  1466.     use Socket;
  1467.     use Net::hostent;
  1468.     $h = gethostbyname("perl.com");  # object return
  1469.     printf "perl.com's real name is %s, address %s\n",
  1470.         $h->name, inet_ntoa($h->addr);</PRE>
  1471. <P>Here's how to do this using the Class::Struct module.
  1472. The crux is going to be this call:</P>
  1473. <PRE>
  1474.     struct 'Net::hostent' => [          # note bracket
  1475.         name       => '$',
  1476.         aliases    => '@',
  1477.         addrtype   => '$',
  1478.         'length'   => '$',
  1479.         addr_list  => '@',
  1480.      ];</PRE>
  1481. <P>Which creates object methods of those names and types.
  1482. It even creates a <CODE>new()</CODE> method for us.</P>
  1483. <P>We could also have implemented our object this way:</P>
  1484. <PRE>
  1485.     struct 'Net::hostent' => {          # note brace
  1486.         name       => '$',
  1487.         aliases    => '@',
  1488.         addrtype   => '$',
  1489.         'length'   => '$',
  1490.         addr_list  => '@',
  1491.      };</PRE>
  1492. <P>and then Class::Struct would have used an anonymous hash as the object
  1493. type, instead of an anonymous array.  The array is faster and smaller,
  1494. but the hash works out better if you eventually want to do inheritance.
  1495. Since for this struct-like object we aren't planning on inheritance,
  1496. this time we'll opt for better speed and size over better flexibility.</P>
  1497. <P>Here's the whole implementation:</P>
  1498. <PRE>
  1499.     package Net::hostent;
  1500.     use strict;</PRE>
  1501. <PRE>
  1502.     BEGIN {
  1503.         use Exporter   ();
  1504.         our @EXPORT      = qw(gethostbyname gethostbyaddr gethost);
  1505.         our @EXPORT_OK   = qw(
  1506.                                $h_name         @h_aliases
  1507.                                $h_addrtype     $h_length
  1508.                                @h_addr_list    $h_addr
  1509.                            );
  1510.         our %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
  1511.     }
  1512.     our @EXPORT_OK;</PRE>
  1513. <PRE>
  1514.     # Class::Struct forbids use of @ISA
  1515.     sub import { goto &Exporter::import }</PRE>
  1516. <PRE>
  1517.     use Class::Struct qw(struct);
  1518.     struct 'Net::hostent' => [
  1519.        name        => '$',
  1520.        aliases     => '@',
  1521.        addrtype    => '$',
  1522.        'length'    => '$',
  1523.        addr_list   => '@',
  1524.     ];</PRE>
  1525. <PRE>
  1526.     sub addr { shift->addr_list->[0] }</PRE>
  1527. <PRE>
  1528.     sub populate (@) {
  1529.         return unless @_;
  1530.         my $hob = new();  # Class::Struct made this!
  1531.         $h_name     =    $hob->[0]              = $_[0];
  1532.         @h_aliases  = @{ $hob->[1] } = split ' ', $_[1];
  1533.         $h_addrtype =    $hob->[2]              = $_[2];
  1534.         $h_length   =    $hob->[3]              = $_[3];
  1535.         $h_addr     =                             $_[4];
  1536.         @h_addr_list = @{ $hob->[4] } =         @_[ (4 .. $#_) ];
  1537.         return $hob;
  1538.     }</PRE>
  1539. <PRE>
  1540.     sub gethostbyname ($)  { populate(CORE::gethostbyname(shift)) }</PRE>
  1541. <PRE>
  1542.     sub gethostbyaddr ($;$) {
  1543.         my ($addr, $addrtype);
  1544.         $addr = shift;
  1545.         require Socket unless @_;
  1546.         $addrtype = @_ ? shift : Socket::AF_INET();
  1547.         populate(CORE::gethostbyaddr($addr, $addrtype))
  1548.     }</PRE>
  1549. <PRE>
  1550.     sub gethost($) {
  1551.         if ($_[0] =~ /^\d+(?:\.\d+(?:\.\d+(?:\.\d+)?)?)?$/) {
  1552.            require Socket;
  1553.            &gethostbyaddr(Socket::inet_aton(shift));
  1554.         } else {
  1555.            &gethostbyname;
  1556.         }
  1557.     }</PRE>
  1558. <PRE>
  1559.     1;</PRE>
  1560. <P>We've snuck in quite a fair bit of other concepts besides just dynamic
  1561. class creation, like overriding core functions, import/export bits,
  1562. function prototyping, short-cut function call via <CODE>&whatever</CODE>, and
  1563. function replacement with <CODE>goto &whatever</CODE>.  These all mostly make
  1564. sense from the perspective of a traditional module, but as you can see,
  1565. we can also use them in an object module.</P>
  1566. <P>You can look at other object-based, struct-like overrides of core
  1567. functions in the 5.004 release of Perl in File::stat, Net::hostent,
  1568. Net::netent, Net::protoent, Net::servent, Time::gmtime, Time::localtime,
  1569. User::grent, and User::pwent.  These modules have a final component
  1570. that's all lowercase, by convention reserved for compiler pragmas,
  1571. because they affect the compilation and change a builtin function.
  1572. They also have the type names that a C programmer would most expect.</P>
  1573. <P>
  1574. <H2><A NAME="data members as variables">Data Members as Variables</A></H2>
  1575. <P>If you're used to C++ objects, then you're accustomed to being able to
  1576. get at an object's data members as simple variables from within a method.
  1577. The Alias module provides for this, as well as a good bit more, such
  1578. as the possibility of private methods that the object can call but folks
  1579. outside the class cannot.</P>
  1580. <P>Here's an example of creating a Person using the Alias module.
  1581. When you update these magical instance variables, you automatically
  1582. update value fields in the hash.  Convenient, eh?</P>
  1583. <PRE>
  1584.     package Person;</PRE>
  1585. <PRE>
  1586.     # this is the same as before...
  1587.     sub new {
  1588.          my $that  = shift;
  1589.          my $class = ref($that) || $that;
  1590.          my $self = {
  1591.             NAME  => undef,
  1592.             AGE   => undef,
  1593.             PEERS => [],
  1594.         };
  1595.         bless($self, $class);
  1596.         return $self;
  1597.     }</PRE>
  1598. <PRE>
  1599.     use Alias qw(attr);
  1600.     our ($NAME, $AGE, $PEERS);</PRE>
  1601. <PRE>
  1602.     sub name {
  1603.         my $self = attr shift;
  1604.         if (@_) { $NAME = shift; }
  1605.         return    $NAME;
  1606.     }</PRE>
  1607. <PRE>
  1608.     sub age {
  1609.         my $self = attr shift;
  1610.         if (@_) { $AGE = shift; }
  1611.         return    $AGE;
  1612.     }</PRE>
  1613. <PRE>
  1614.     sub peers {
  1615.         my $self = attr shift;
  1616.         if (@_) { @PEERS = @_; }
  1617.         return    @PEERS;
  1618.     }</PRE>
  1619. <PRE>
  1620.     sub exclaim {
  1621.         my $self = attr shift;
  1622.         return sprintf "Hi, I'm %s, age %d, working with %s",
  1623.             $NAME, $AGE, join(", ", @PEERS);
  1624.     }</PRE>
  1625. <PRE>
  1626.     sub happy_birthday {
  1627.         my $self = attr shift;
  1628.         return ++$AGE;
  1629.     }</PRE>
  1630. <P>The need for the <A HREF="../../lib/Pod/perlfunc.html#item_our"><CODE>our</CODE></A> declaration is because what Alias does
  1631. is play with package globals with the same name as the fields.  To use
  1632. globals while <CODE>use strict</CODE> is in effect, you have to predeclare them.
  1633. These package variables are localized to the block enclosing the <CODE>attr()</CODE>
  1634. call just as if you'd used a <A HREF="../../lib/Pod/perlfunc.html#item_local"><CODE>local()</CODE></A> on them.  However, that means that
  1635. they're still considered global variables with temporary values, just
  1636. as with any other local().</P>
  1637. <P>It would be nice to combine Alias with
  1638. something like Class::Struct or Class::MethodMaker.</P>
  1639. <P>
  1640. <H2><A NAME="notes">NOTES</A></H2>
  1641. <P>
  1642. <H2><A NAME="object terminology">Object Terminology</A></H2>
  1643. <P>In the various OO literature, it seems that a lot of different words
  1644. are used to describe only a few different concepts.  If you're not
  1645. already an object programmer, then you don't need to worry about all
  1646. these fancy words.  But if you are, then you might like to know how to
  1647. get at the same concepts in Perl.</P>
  1648. <P>For example, it's common to call an object an <EM>instance</EM> of a class
  1649. and to call those objects' methods <EM>instance methods</EM>.  Data fields
  1650. peculiar to each object are often called <EM>instance data</EM> or <EM>object
  1651. attributes</EM>, and data fields common to all members of that class are
  1652. <EM>class data</EM>, <EM>class attributes</EM>, or <EM>static data members</EM>.</P>
  1653. <P>Also, <EM>base class</EM>, <EM>generic class</EM>, and <EM>superclass</EM> all describe
  1654. the same notion, whereas <EM>derived class</EM>, <EM>specific class</EM>, and
  1655. <EM>subclass</EM> describe the other related one.</P>
  1656. <P>C++ programmers have <EM>static methods</EM> and <EM>virtual methods</EM>,
  1657. but Perl only has <EM>class methods</EM> and <EM>object methods</EM>.
  1658. Actually, Perl only has methods.  Whether a method gets used
  1659. as a class or object method is by usage only.  You could accidentally
  1660. call a class method (one expecting a string argument) on an
  1661. object (one expecting a reference), or vice versa.</P>
  1662. <P>From the C++ perspective, all methods in Perl are virtual.
  1663. This, by the way, is why they are never checked for function
  1664. prototypes in the argument list as regular builtin and user-defined
  1665. functions can be.</P>
  1666. <P>Because a class is itself something of an object, Perl's classes can be
  1667. taken as describing both a ``class as meta-object'' (also called <EM>object
  1668. factory</EM>) philosophy and the ``class as type definition'' (<EM>declaring</EM>
  1669. behaviour, not <EM>defining</EM> mechanism) idea.  C++ supports the latter
  1670. notion, but not the former.</P>
  1671. <P>
  1672. <HR>
  1673. <H1><A NAME="see also">SEE ALSO</A></H1>
  1674. <P>The following manpages will doubtless provide more
  1675. background for this one:
  1676. <A HREF="../../lib/Pod/perlmod.html">the perlmod manpage</A>,
  1677. <A HREF="../../lib/Pod/perlref.html">the perlref manpage</A>,
  1678. <A HREF="../../lib/Pod/perlobj.html">the perlobj manpage</A>,
  1679. <A HREF="../../lib/Pod/perlbot.html">the perlbot manpage</A>,
  1680. <A HREF="../../lib/Pod/perltie.html">the perltie manpage</A>,
  1681. and
  1682. <A HREF="../../lib/overload.html">the overload manpage</A>.</P>
  1683. <P>
  1684. <HR>
  1685. <H1><A NAME="author and copyright">AUTHOR AND COPYRIGHT</A></H1>
  1686. <P>Copyright (c) 1997, 1998 Tom Christiansen 
  1687. All rights reserved.</P>
  1688. <P>When included as part of the Standard Version of Perl, or as part of
  1689. its complete documentation whether printed or otherwise, this work
  1690. may be distributed only under the terms of Perl's Artistic License.
  1691. Any distribution of this file or derivatives thereof <EM>outside</EM>
  1692. of that package require that special arrangements be made with
  1693. copyright holder.</P>
  1694. <P>Irrespective of its distribution, all code examples in this file
  1695. are hereby placed into the public domain.  You are permitted and
  1696. encouraged to use this code in your own programs for fun
  1697. or for profit as you see fit.  A simple comment in the code giving
  1698. credit would be courteous but is not required.</P>
  1699. <P>
  1700. <HR>
  1701. <H1><A NAME="copyright">COPYRIGHT</A></H1>
  1702. <P>
  1703. <H2><A NAME="acknowledgments">Acknowledgments</A></H2>
  1704. <P>Thanks to
  1705. Larry Wall,
  1706. Roderick Schertler,
  1707. Gurusamy Sarathy,
  1708. Dean Roehrich,
  1709. Raphael Manfredi,
  1710. Brent Halsey,
  1711. Greg Bacon,
  1712. Brad Appleton,
  1713. and many others for their helpful comments.</P>
  1714. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  1715. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  1716. <STRONG><P CLASS=block> perltoot - Tom's object-oriented tutorial for perl</P></STRONG>
  1717. </TD></TR>
  1718. </TABLE>
  1719.  
  1720. </BODY>
  1721.  
  1722. </HTML>
  1723.