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