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">
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:" />
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"> perltoot - Tom's object-oriented tutorial for perl
</span></strong></big>
17 <p><a name=
"__index__"></a></p>
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>
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>
35 <li><a href=
"#class_data">Class Data
</a></li>
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>
44 <li><a href=
"#aggregation">Aggregation
</a></li>
45 <li><a href=
"#inheritance">Inheritance
</a></li>
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>
53 <li><a href=
"#alternate_object_representations">Alternate Object Representations
</a></li>
56 <li><a href=
"#arrays_as_objects">Arrays as Objects
</a></li>
57 <li><a href=
"#closures_as_objects">Closures as Objects
</a></li>
60 <li><a href=
"#autoload__proxy_methods">AUTOLOAD: Proxy Methods
</a></li>
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>
67 <li><a href=
"#metaclassical_tools">Metaclassical Tools
</a></li>
70 <li><a href=
"#class__struct">Class::Struct
</a></li>
71 <li><a href=
"#data_members_as_variables">Data Members as Variables
</a></li>
74 <li><a href=
"#notes">NOTES
</a></li>
77 <li><a href=
"#object_terminology">Object Terminology
</a></li>
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>
85 <li><a href=
"#acknowledgments">Acknowledgments
</a></li>
94 <h1><a name=
"name">NAME
</a></h1>
95 <p>perltoot - Tom's object-oriented tutorial for perl
</p>
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
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>
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>
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>
185 name =
> "Jason
",
187 peers =
> [
"Norbert
",
"Rhys
",
"Phineas
"],
189 <p>If you felt like it, you could add a bit of visual distinction
190 by up-casing the hash keys:
</p>
193 NAME =
> "Jason
",
195 PEERS =
> [
"Norbert
",
"Rhys
",
"Phineas
"],
197 <p>And so you could get at
<code>$rec-
>{NAME}
</code> to find ``Jason'', or
198 <code>@{ $rec-
>{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>
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>
224 $him = Person-
>new();
225 $him-
>name(
"Jason
");
227 $him-
>peers(
"Norbert
",
"Rhys
",
"Phineas
" );
</pre>
229 push @All_Recs, $him; # save object in array for later
</pre>
231 printf
"%s is %d years old.\n
", $him-
>name, $him-
>age;
232 print
"His peers are:
", join(
",
", $him-
>peers),
"\n
";
</pre>
234 printf
"Last rec's name is %s\n
", $All_Recs[-
1]-
>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
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>
253 ##################################################
254 ## the object constructor (simplistic version) ##
255 ##################################################
258 $self-
>{NAME} = undef;
259 $self-
>{AGE} = undef;
260 $self-
>{PEERS} = [];
261 bless($self); # but see below
265 ##############################################
266 ## methods to access per-object data ##
268 ## With args, they set the value. Without ##
269 ## any, they only retrieve it/them. ##
270 ##############################################
</pre>
274 if (@_) { $self-
>{NAME} = shift }
275 return $self-
>{NAME};
280 if (@_) { $self-
>{AGE} = shift }
281 return $self-
>{AGE};
286 if (@_) { @{ $self-
>{PEERS} } = @_ }
287 return @{ $self-
>{PEERS} };
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>
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>
309 $self-
>{NAME} = undef;
310 $self-
>{AGE} = undef;
311 $self-
>{PEERS} = [];
312 bless ($self, $class);
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>
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
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
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>
353 $this-
>{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>
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>
387 return sprintf
"Hi, I'm %s, age %d, working with %s
",
388 $self-
>{NAME}, $self-
>{AGE}, join(
",
", @{$self-
>{PEERS}});
390 <p>Or maybe even one like this:
</p>
394 return ++$self-
>{AGE};
396 <p>Some might argue that one should go at these this way:
</p>
400 return sprintf
"Hi, I'm %s, age %d, working with %s
",
401 $self-
>name, $self-
>age, join(
",
", $self-
>peers);
406 return $self-
>age( $self-
>age() +
1 );
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>
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>
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>
455 $self-
>{NAME} = undef;
456 $self-
>{AGE} = undef;
457 $self-
>{PEERS} = [];
458 bless ($self, $class);
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>
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
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
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>
504 $self-
>{NAME} = undef;
505 $self-
>{AGE} = undef;
506 $self-
>{PEERS} = [];
507 #
"private
" data
508 $self-
>{
"_CENSUS
"} = \$Census;
509 bless ($self, $class);
510 ++ ${ $self-
>{
"_CENSUS
"} };
517 return ${ $self-
>{
"_CENSUS
"} };
525 -- ${ $self-
>{
"_CENSUS
"} };
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>
540 my $Debugging =
0;
</pre>
541 <p>Now add a new class method to access the variable.
</p>
545 if (ref $class) { confess
"Class method called as object method
" }
546 unless (@_ ==
1) { confess
"usage: CLASSNAME-
>debug(level)
" }
549 <p>Now fix up DESTROY to murmur a bit as the moribund object expires:
</p>
553 if ($Debugging) { carp
"Destroying $self
" . $self-
>name }
554 -- ${ $self-
>{
"_CENSUS
"} };
556 <p>One could conceivably make a per-object debug state. That
557 way you could call both of these:
</p>
559 Person-
>debug(
1); # entire class
560 $him-
>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>
567 confess
"usage: thing-
>debug(level)
" unless @_ ==
1;
570 $self-
>{
"_DEBUG
"} = $level; # just myself
572 $Debugging = $level; # whole class
578 if ($Debugging || $self-
>{
"_DEBUG
"}) {
579 carp
"Destroying $self
" . $self-
>name;
581 -- ${ $self-
>{
"_CENSUS
"} };
583 <p>What happens if a derived class (which we'll call Employee) inherits
584 methods from this Person base class? Then
<code>Employee-
>debug()
</code>, when called
585 as a class method, manipulates $Person::Debugging not $Employee::Debugging.
</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>
599 print
"All persons are going away now.\n
";
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>
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>
619 Person - class to implement people
</pre>
621 =head1 SYNOPSIS
</pre>
628 $ob = Person-
>new;
629 $count = Person-
>population;
</pre>
631 #######################
632 # object data methods #
633 #######################
</pre>
637 $years = $ob-
>age;
638 @pals = $ob-
>peers;
</pre>
641 $ob-
>name(
"Jason
");
643 $ob-
>peers(
"Norbert
",
"Rhys
",
"Phineas
" );
</pre>
645 ########################
646 # other object methods #
647 ########################
</pre>
649 $phrase = $ob-
>exclaim;
650 $ob-
>happy_birthday;
</pre>
652 =head1 DESCRIPTION
</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>
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>
674 $him = Person-
>new();
675 $him-
>fullname-
>title(
"St
");
676 $him-
>fullname-
>christian(
"Thomas
");
677 $him-
>fullname-
>surname(
"Aquinas
");
678 $him-
>fullname-
>nickname(
"Tommy
");
679 printf
"His normal name is %s\n
", $him-
>name;
680 printf
"But his real name is %s\n
", $him-
>fullname-
>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>
687 $self-
>{FULLNAME} = Fullname-
>new();
688 $self-
>{AGE} = undef;
689 $self-
>{PEERS} = [];
690 $self-
>{
"_CENSUS
"} = \$Census;
691 bless ($self, $class);
692 ++ ${ $self-
>{
"_CENSUS
"} };
698 return $self-
>{FULLNAME};
700 <p>Then to support old code, define Person::name() this way:
</p>
704 return $self-
>{FULLNAME}-
>nickname(@_)
705 || $self-
>{FULLNAME}-
>christian(@_);
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>
718 CHRISTIAN =
> undef,
722 bless ($self, $class);
728 if (@_) { $self-
>{CHRISTIAN} = shift }
729 return $self-
>{CHRISTIAN};
734 if (@_) { $self-
>{SURNAME} = shift }
735 return $self-
>{SURNAME};
740 if (@_) { $self-
>{NICK} = shift }
741 return $self-
>{NICK};
746 if (@_) { $self-
>{TITLE} = shift }
747 return $self-
>{TITLE};
752 my $name = join(
" ", @$self{'CHRISTIAN', 'SURNAME'});
753 if ($self-
>{TITLE}) {
754 $name = $self-
>{TITLE} .
" " . $name;
760 <p>Finally, here's the test program:
</p>
765 sub END { show_census() }
</pre>
768 printf
"Current population: %d\n
", Person-
>population;
771 Person-
>debug(
1);
</pre>
775 my $him = Person-
>new();
</pre>
777 $him-
>fullname-
>christian(
"Thomas
");
778 $him-
>fullname-
>surname(
"Aquinas
");
779 $him-
>fullname-
>nickname(
"Tommy
");
780 $him-
>fullname-
>title(
"St
");
781 $him-
>age(
1);
</pre>
783 printf
"%s is really %s.\n
", $him-
>name, $him-
>fullname-
>as_string;
784 printf
"%s's age: %d.\n
", $him-
>name, $him-
>age;
785 $him-
>happy_birthday;
786 printf
"%s's age: %d.\n
", $him-
>name, $him-
>age;
</pre>
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>
817 @ISA = (
"Person
");
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>
830 my $empl = Employee-
>new();
831 $empl-
>name(
"Jason
");
833 printf
"%s is age %d.\n
", $empl-
>name, $empl-
>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-
>new()
</code> method and the
<code>Employee-
>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,
852 Method Call Resulting Function Call
853 ----------- ------------------------
854 Person-
>new() Person::new(
"Person
")
855 Employee-
>new() Person::new(
"Employee
")
</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
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>
868 if (@_) { $self-
>{SALARY} = shift }
869 return $self-
>{SALARY};
874 if (@_) { $self-
>{ID} = shift }
875 return $self-
>{ID};
880 if (@_) { $self-
>{START_DATE} = shift }
881 return $self-
>{START_DATE};
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>
892 $empl-
>peers(
"Peter
",
"Paul
",
"Mary
");
893 printf
"His peers are: %s\n
", join(
",
", $empl-
>peers);
</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>
901 if (@_) { @{ $self-
>{PEERS} } = @_ }
902 return map {
"PEON=\U$_
" } @{ $self-
>{PEERS} };
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>
917 my $Debugging =
0;
</pre>
921 confess
"usage: thing-
>debug(level)
" unless @_ ==
1;
924 $self-
>{
"_DEBUG
"} = $level;
926 $Debugging = $level; # whole class
928 Person::debug($self, $Debugging); # don't really do this
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>
935 Person-
>debug($Debugging);
</pre>
936 <p>But even that's got too much hard-coded. It's somewhat better to say
</p>
938 $self-
>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>
947 $self-
>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>
961 @ISA = qw(Employee);
</pre>
962 <p>And here's the test program:
</p>
967 Boss-
>debug(
1);
</pre>
969 my $boss = Boss-
>new();
</pre>
971 $boss-
>fullname-
>title(
"Don
");
972 $boss-
>fullname-
>surname(
"Pichon Alvarez
");
973 $boss-
>fullname-
>christian(
"Federico Jesus
");
974 $boss-
>fullname-
>nickname(
"Fred
");
</pre>
977 $boss-
>peers(
"Frank
",
"Felipe
",
"Faust
");
</pre>
979 printf
"%s is age %d.\n
", $boss-
>fullname-
>as_string, $boss-
>age;
980 printf
"His peers are: %s\n
", join(
",
", $boss-
>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>
986 print
"Here's the boss:\n
";
987 print Dumper($boss);
</pre>
988 <p>Which shows us something like this:
</p>
993 FULLNAME =
> bless( {
995 SURNAME =
> 'Pichon Alvarez',
997 CHRISTIAN =
> 'Federico Jesus'
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>
1016 my $self = $class-
>SUPER::new();
1017 $self-
>{SALARY} = undef;
1018 $self-
>{ID} = undef;
1019 $self-
>{START_DATE} = undef;
1020 bless ($self, $class); # reconsecrate
1023 <p>Now if you dump out an Employee or Boss object, you'll find
1024 that new fields show up there now.
</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>
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>
1047 my $ob = Third-
>new();
1048 $ob-
>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>
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>
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>
1099 $has_io = $fd-
>isa(
"IO::Handle
");
1100 $itza_handle = IO::Socket-
>isa(
"IO::Handle
");
</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>
1105 $his_print_method = $obj-
>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>
1109 Some_Module-
>VERSION(
3.0);
1110 $his_vers = $ob-
>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>
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>
1120 our $VERSION = '
1.1';
</pre>
1121 <p>and then in Employee.pm you can say
</p>
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>
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
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>
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>
1151 my($NAME, $AGE, $PEERS) = (
0 ..
2 );
</pre>
1153 ############################################
1154 ## the object constructor (array version) ##
1155 ############################################
1158 $self-
>[$NAME] = undef; # this is unnecessary
1159 $self-
>[$AGE] = undef; # as is this
1160 $self-
>[$PEERS] = []; # but this isn't, really
1167 if (@_) { $self-
>[$NAME] = shift }
1168 return $self-
>[$NAME];
1173 if (@_) { $self-
>[$AGE] = shift }
1174 return $self-
>[$AGE];
1179 if (@_) { @{ $self-
>[$PEERS] } = @_ }
1180 return @{ $self-
>[$PEERS] };
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
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>
1217 $him = Person-
>new();
1218 $him-
>name(
"Jason
");
1220 $him-
>peers( [
"Norbert
",
"Rhys
",
"Phineas
" ] );
1221 printf
"%s is %d years old.\n
", $him-
>name, $him-
>age;
1222 print
"His peers are:
", join(
",
", @{$him-
>peers}),
"\n
";
</pre>
1223 <p>but the implementation would be radically, perhaps even sublimely
1226 package Person;
</pre>
1237 if (@_) { $self-
>{$field} = shift }
1238 return $self-
>{$field};
1240 bless($closure, $class);
1244 sub name {
&{ $_[
0] }(
"NAME
", @_[
1 .. $#_ ] ) }
1245 sub age {
&{ $_[
0] }(
"AGE
", @_[
1 .. $#_ ] ) }
1246 sub peers {
&{ $_[
0] }(
"PEERS
", @_[
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-
>name(
"Jason
")
</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>&{$_[
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
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
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>
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
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
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>
1340 our $AUTOLOAD; # it's a package global
</pre>
1351 _permitted =
> \%fields,
1354 bless $self, $class;
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>
1371 my $type = ref($self)
1372 or croak
"$self is not an object
";
</pre>
1374 my $name = $AUTOLOAD;
1375 $name =~ s/.*://; # strip fully-qualified portion
</pre>
1377 unless (exists $self-
>{_permitted}-
>{$name} ) {
1378 croak
"Can't access `$name' field in class $type
";
1382 return $self-
>{$name} = shift;
1384 return $self-
>{$name};
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>
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>
1403 our @ISA = qw(Person);
</pre>
1412 my $self = $class-
>SUPER::new();
1414 foreach $element (keys %fields) {
1415 $self-
>{_permitted}-
>{$element} = $fields{$element};
1417 @{$self}{keys %fields} = values %fields;
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>
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>
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>
1454 use Class::Struct qw(struct);
1455 use Jobbie; # user-defined; see below
</pre>
1457 struct 'Fred' =
> {
1460 profession =
> 'Jobbie', # does not call Jobbie-
>new()
1463 $ob = Fred-
>new(profession =
> Jobbie-
>new());
1464 $ob-
>one(
"hmmmm
");
</pre>
1466 $ob-
>many(
0,
"here
");
1467 $ob-
>many(
1,
"you
");
1468 $ob-
>many(
2,
"go
");
1469 print
"Just set:
", $ob-
>many(
2),
"\n
";
</pre>
1471 $ob-
>profession-
>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>
1486 $h = gethostbyname(
"perl.com
"); # object return
1487 printf
"perl.com's real name is %s, address %s\n
",
1488 $h-
>name, inet_ntoa($h-
>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>
1492 struct 'Net::hostent' =
> [ # note bracket
1497 addr_list =
> '@',
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>
1503 struct 'Net::hostent' =
> { # note brace
1508 addr_list =
> '@',
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>
1517 package Net::hostent;
1522 our @EXPORT = qw(gethostbyname gethostbyaddr gethost);
1523 our @EXPORT_OK = qw(
1525 $h_addrtype $h_length
1526 @h_addr_list $h_addr
1528 our %EXPORT_TAGS = ( FIELDS =
> [ @EXPORT_OK, @EXPORT ] );
1530 our @EXPORT_OK;
</pre>
1532 # Class::Struct forbids use of @ISA
1533 sub import { goto
&Exporter::import }
</pre>
1535 use Class::Struct qw(struct);
1536 struct 'Net::hostent' =
> [
1541 addr_list =
> '@',
1544 sub addr { shift-
>addr_list-
>[
0] }
</pre>
1548 my $hob = new(); # Class::Struct made this!
1549 $h_name = $hob-
>[
0] = $_[
0];
1550 @h_aliases = @{ $hob-
>[
1] } = split ' ', $_[
1];
1551 $h_addrtype = $hob-
>[
2] = $_[
2];
1552 $h_length = $hob-
>[
3] = $_[
3];
1554 @h_addr_list = @{ $hob-
>[
4] } = @_[ (
4 .. $#_) ];
1558 sub gethostbyname ($) { populate(CORE::gethostbyname(shift)) }
</pre>
1560 sub gethostbyaddr ($;$) {
1561 my ($addr, $addrtype);
1563 require Socket unless @_;
1564 $addrtype = @_ ? shift : Socket::AF_INET();
1565 populate(CORE::gethostbyaddr($addr, $addrtype))
1569 if ($_[
0] =~ /^\d+(?:\.\d+(?:\.\d+(?:\.\d+)?)?)?$/) {
1571 &gethostbyaddr(Socket::inet_aton(shift));
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>&whatever
</code>, and
1581 function replacement with
<code>goto
&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>
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>
1603 package Person;
</pre>
1605 # this is the same as before...
1613 bless($self, $class);
1618 our ($NAME, $AGE, $PEERS);
</pre>
1621 my $self = attr shift;
1622 if (@_) { $NAME = shift; }
1627 my $self = attr shift;
1628 if (@_) { $AGE = shift; }
1633 my $self = attr shift;
1634 if (@_) { @PEERS = @_; }
1639 my $self = attr shift;
1640 return sprintf
"Hi, I'm %s, age %d, working with %s
",
1641 $NAME, $AGE, join(
",
", @PEERS);
1644 sub happy_birthday {
1645 my $self = attr shift;
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>
1660 <h1><a name=
"notes">NOTES
</a></h1>
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>
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
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>
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>
1727 <h1><a name=
"copyright">COPYRIGHT
</a></h1>
1730 <h2><a name=
"acknowledgments">Acknowledgments
</a></h2>
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"> perltoot - Tom's object-oriented tutorial for perl
</span></strong></big>