1PERLTOOT(1)            Perl Programmers Reference Guide            PERLTOOT(1)
2
3
4

NAME

6       perltoot - Tom's object-oriented tutorial for perl
7

DESCRIPTION

9       Object-oriented programming is a big seller these days.  Some managers
10       would rather have objects than sliced bread.  Why is that?  What's so
11       special about an object?  Just what is an object anyway?
12
13       An object is nothing but a way of tucking away complex behaviours into
14       a neat little easy-to-use bundle.  (This is what professors call
15       abstraction.) Smart people who have nothing to do but sit around for
16       weeks on end figuring out really hard problems make these nifty objects
17       that even regular people can use. (This is what professors call
18       software reuse.)  Users (well, programmers) can play with this little
19       bundle all they want, but they aren't to open it up and mess with the
20       insides.  Just like an expensive piece of hardware, the contract says
21       that you void the warranty if you muck with the cover.  So don't do
22       that.
23
24       The heart of objects is the class, a protected little private namespace
25       full of data and functions.  A class is a set of related routines that
26       addresses some problem area.  You can think of it as a user-defined
27       type.  The Perl package mechanism, also used for more traditional
28       modules, is used for class modules as well.  Objects "live" in a class,
29       meaning that they belong to some package.
30
31       More often than not, the class provides the user with little bundles.
32       These bundles are objects.  They know whose class they belong to, and
33       how to behave.  Users ask the class to do something, like "give me an
34       object."  Or they can ask one of these objects to do something.  Asking
35       a class to do something for you is calling a class method.  Asking an
36       object to do something for you is calling an object method.  Asking
37       either a class (usually) or an object (sometimes) to give you back an
38       object is calling a constructor, which is just a kind of method.
39
40       That's all well and good, but how is an object different from any other
41       Perl data type?  Just what is an object really; that is, what's its
42       fundamental type?  The answer to the first question is easy.  An object
43       is different from any other data type in Perl in one and only one way:
44       you may dereference it using not merely string or numeric subscripts as
45       with simple arrays and hashes, but with named subroutine calls.  In a
46       word, with methods.
47
48       The answer to the second question is that it's a reference, and not
49       just any reference, mind you, but one whose referent has been bless()ed
50       into a particular class (read: package).  What kind of reference?
51       Well, the answer to that one is a bit less concrete.  That's because in
52       Perl the designer of the class can employ any sort of reference they'd
53       like as the underlying intrinsic data type.  It could be a scalar, an
54       array, or a hash reference.  It could even be a code reference.  But
55       because of its inherent flexibility, an object is usually a hash
56       reference.
57

Creating a Class

59       Before you create a class, you need to decide what to name it.  That's
60       because the class (package) name governs the name of the file used to
61       house it, just as with regular modules.  Then, that class (package)
62       should provide one or more ways to generate objects.  Finally, it
63       should provide mechanisms to allow users of its objects to indirectly
64       manipulate these objects from a distance.
65
66       For example, let's make a simple Person class module.  It gets stored
67       in the file Person.pm.  If it were called a Happy::Person class, it
68       would be stored in the file Happy/Person.pm, and its package would
69       become Happy::Person instead of just Person.  (On a personal computer
70       not running Unix or Plan 9, but something like Mac OS or VMS, the
71       directory separator may be different, but the principle is the same.)
72       Do not assume any formal relationship between modules based on their
73       directory names.  This is merely a grouping convenience, and has no
74       effect on inheritance, variable accessibility, or anything else.
75
76       For this module we aren't going to use Exporter, because we're a well-
77       behaved class module that doesn't export anything at all.  In order to
78       manufacture objects, a class needs to have a constructor method.  A
79       constructor gives you back not just a regular data type, but a brand-
80       new object in that class.  This magic is taken care of by the bless()
81       function, whose sole purpose is to enable its referent to be used as an
82       object.  Remember: being an object really means nothing more than that
83       methods may now be called against it.
84
85       While a constructor may be named anything you'd like, most Perl
86       programmers seem to like to call theirs new().  However, new() is not a
87       reserved word, and a class is under no obligation to supply such.  Some
88       programmers have also been known to use a function with the same name
89       as the class as the constructor.
90
91   Object Representation
92       By far the most common mechanism used in Perl to represent a Pascal
93       record, a C struct, or a C++ class is an anonymous hash.  That's
94       because a hash has an arbitrary number of data fields, each
95       conveniently accessed by an arbitrary name of your own devising.
96
97       If you were just doing a simple struct-like emulation, you would likely
98       go about it something like this:
99
100           $rec = {
101               name  => "Jason",
102               age   => 23,
103               peers => [ "Norbert", "Rhys", "Phineas"],
104           };
105
106       If you felt like it, you could add a bit of visual distinction by up-
107       casing the hash keys:
108
109           $rec = {
110               NAME  => "Jason",
111               AGE   => 23,
112               PEERS => [ "Norbert", "Rhys", "Phineas"],
113           };
114
115       And so you could get at "$rec->{NAME}" to find "Jason", or "@{
116       $rec->{PEERS} }" to get at "Norbert", "Rhys", and "Phineas".  (Have you
117       ever noticed how many 23-year-old programmers seem to be named "Jason"
118       these days? :-)
119
120       This same model is often used for classes, although it is not
121       considered the pinnacle of programming propriety for folks from outside
122       the class to come waltzing into an object, brazenly accessing its data
123       members directly.  Generally speaking, an object should be considered
124       an opaque cookie that you use object methods to access.  Visually,
125       methods look like you're dereffing a reference using a function name
126       instead of brackets or braces.
127
128   Class Interface
129       Some languages provide a formal syntactic interface to a class's
130       methods, but Perl does not.  It relies on you to read the documentation
131       of each class.  If you try to call an undefined method on an object,
132       Perl won't complain, but the program will trigger an exception while
133       it's running.  Likewise, if you call a method expecting a prime number
134       as its argument with a non-prime one instead, you can't expect the
135       compiler to catch this.  (Well, you can expect it all you like, but
136       it's not going to happen.)
137
138       Let's suppose you have a well-educated user of your Person class,
139       someone who has read the docs that explain the prescribed interface.
140       Here's how they might use the Person class:
141
142           use Person;
143
144           $him = Person->new();
145           $him->name("Jason");
146           $him->age(23);
147           $him->peers( "Norbert", "Rhys", "Phineas" );
148
149           push @All_Recs, $him;  # save object in array for later
150
151           printf "%s is %d years old.\n", $him->name, $him->age;
152           print "His peers are: ", join(", ", $him->peers), "\n";
153
154           printf "Last rec's name is %s\n", $All_Recs[-1]->name;
155
156       As you can see, the user of the class doesn't know (or at least, has no
157       business paying attention to the fact) that the object has one
158       particular implementation or another.  The interface to the class and
159       its objects is exclusively via methods, and that's all the user of the
160       class should ever play with.
161
162   Constructors and Instance Methods
163       Still, someone has to know what's in the object.  And that someone is
164       the class.  It implements methods that the programmer uses to access
165       the object.  Here's how to implement the Person class using the
166       standard hash-ref-as-an-object idiom.  We'll make a class method called
167       new() to act as the constructor, and three object methods called
168       name(), age(), and peers() to get at per-object data hidden away in our
169       anonymous hash.
170
171           package Person;
172           use strict;
173
174           ##################################################
175           ## the object constructor (simplistic version)  ##
176           ##################################################
177           sub new {
178               my $self  = {};
179               $self->{NAME}   = undef;
180               $self->{AGE}    = undef;
181               $self->{PEERS}  = [];
182               bless($self);           # but see below
183               return $self;
184           }
185
186           ##############################################
187           ## methods to access per-object data        ##
188           ##                                          ##
189           ## With args, they set the value.  Without  ##
190           ## any, they only retrieve it/them.         ##
191           ##############################################
192
193           sub name {
194               my $self = shift;
195               if (@_) { $self->{NAME} = shift }
196               return $self->{NAME};
197           }
198
199           sub age {
200               my $self = shift;
201               if (@_) { $self->{AGE} = shift }
202               return $self->{AGE};
203           }
204
205           sub peers {
206               my $self = shift;
207               if (@_) { @{ $self->{PEERS} } = @_ }
208               return @{ $self->{PEERS} };
209           }
210
211           1;  # so the require or use succeeds
212
213       We've created three methods to access an object's data, name(), age(),
214       and peers().  These are all substantially similar.  If called with an
215       argument, they set the appropriate field; otherwise they return the
216       value held by that field, meaning the value of that hash key.
217
218   Planning for the Future: Better Constructors
219       Even though at this point you may not even know what it means, someday
220       you're going to worry about inheritance.  (You can safely ignore this
221       for now and worry about it later if you'd like.)  To ensure that this
222       all works out smoothly, you must use the double-argument form of
223       bless().  The second argument is the class into which the referent will
224       be blessed.  By not assuming our own class as the default second
225       argument and instead using the class passed into us, we make our
226       constructor inheritable.
227
228           sub new {
229               my $class = shift;
230               my $self  = {};
231               $self->{NAME}   = undef;
232               $self->{AGE}    = undef;
233               $self->{PEERS}  = [];
234               bless ($self, $class);
235               return $self;
236           }
237
238       That's about all there is for constructors.  These methods bring
239       objects to life, returning neat little opaque bundles to the user to be
240       used in subsequent method calls.
241
242   Destructors
243       Every story has a beginning and an end.  The beginning of the object's
244       story is its constructor, explicitly called when the object comes into
245       existence.  But the ending of its story is the destructor, a method
246       implicitly called when an object leaves this life.  Any per-object
247       clean-up code is placed in the destructor, which must (in Perl) be
248       called DESTROY.
249
250       If constructors can have arbitrary names, then why not destructors?
251       Because while a constructor is explicitly called, a destructor is not.
252       Destruction happens automatically via Perl's garbage collection (GC)
253       system, which is a quick but somewhat lazy reference-based GC system.
254       To know what to call, Perl insists that the destructor be named
255       DESTROY.  Perl's notion of the right time to call a destructor is not
256       well-defined currently, which is why your destructors should not rely
257       on when they are called.
258
259       Why is DESTROY in all caps?  Perl on occasion uses purely uppercase
260       function names as a convention to indicate that the function will be
261       automatically called by Perl in some way.  Others that are called
262       implicitly include BEGIN, END, AUTOLOAD, plus all methods used by tied
263       objects, described in perltie.
264
265       In really good object-oriented programming languages, the user doesn't
266       care when the destructor is called.  It just happens when it's supposed
267       to.  In low-level languages without any GC at all, there's no way to
268       depend on this happening at the right time, so the programmer must
269       explicitly call the destructor to clean up memory and state, crossing
270       their fingers that it's the right time to do so.   Unlike C++, an
271       object destructor is nearly never needed in Perl, and even when it is,
272       explicit invocation is uncalled for.  In the case of our Person class,
273       we don't need a destructor because Perl takes care of simple matters
274       like memory deallocation.
275
276       The only situation where Perl's reference-based GC won't work is when
277       there's a circularity in the data structure, such as:
278
279           $this->{WHATEVER} = $this;
280
281       In that case, you must delete the self-reference manually if you expect
282       your program not to leak memory.  While admittedly error-prone, this is
283       the best we can do right now.  Nonetheless, rest assured that when your
284       program is finished, its objects' destructors are all duly called.  So
285       you are guaranteed that an object eventually gets properly destroyed,
286       except in the unique case of a program that never exits.  (If you're
287       running Perl embedded in another application, this full GC pass happens
288       a bit more frequently--whenever a thread shuts down.)
289
290   Other Object Methods
291       The methods we've talked about so far have either been constructors or
292       else simple "data methods", interfaces to data stored in the object.
293       These are a bit like an object's data members in the C++ world, except
294       that strangers don't access them as data.  Instead, they should only
295       access the object's data indirectly via its methods.  This is an
296       important rule: in Perl, access to an object's data should only be made
297       through methods.
298
299       Perl doesn't impose restrictions on who gets to use which methods.  The
300       public-versus-private distinction is by convention, not syntax.  (Well,
301       unless you use the Alias module described below in "Data Members as
302       Variables".)  Occasionally you'll see method names beginning or ending
303       with an underscore or two.  This marking is a convention indicating
304       that the methods are private to that class alone and sometimes to its
305       closest acquaintances, its immediate subclasses.  But this distinction
306       is not enforced by Perl itself.  It's up to the programmer to behave.
307
308       There's no reason to limit methods to those that simply access data.
309       Methods can do anything at all.  The key point is that they're invoked
310       against an object or a class.  Let's say we'd like object methods that
311       do more than fetch or set one particular field.
312
313           sub exclaim {
314               my $self = shift;
315               return sprintf "Hi, I'm %s, age %d, working with %s",
316                   $self->{NAME}, $self->{AGE}, join(", ", @{$self->{PEERS}});
317           }
318
319       Or maybe even one like this:
320
321           sub happy_birthday {
322               my $self = shift;
323               return ++$self->{AGE};
324           }
325
326       Some might argue that one should go at these this way:
327
328           sub exclaim {
329               my $self = shift;
330               return sprintf "Hi, I'm %s, age %d, working with %s",
331                   $self->name, $self->age, join(", ", $self->peers);
332           }
333
334           sub happy_birthday {
335               my $self = shift;
336               return $self->age( $self->age() + 1 );
337           }
338
339       But since these methods are all executing in the class itself, this may
340       not be critical.  There are tradeoffs to be made.  Using direct hash
341       access is faster (about an order of magnitude faster, in fact), and
342       it's more convenient when you want to interpolate in strings.  But
343       using methods (the external interface) internally shields not just the
344       users of your class but even you yourself from changes in your data
345       representation.
346

Class Data

348       What about "class data", data items common to each object in a class?
349       What would you want that for?  Well, in your Person class, you might
350       like to keep track of the total people alive.  How do you implement
351       that?
352
353       You could make it a global variable called $Person::Census.  But about
354       only reason you'd do that would be if you wanted people to be able to
355       get at your class data directly.  They could just say $Person::Census
356       and play around with it.  Maybe this is ok in your design scheme.  You
357       might even conceivably want to make it an exported variable.  To be
358       exportable, a variable must be a (package) global.  If this were a
359       traditional module rather than an object-oriented one, you might do
360       that.
361
362       While this approach is expected in most traditional modules, it's
363       generally considered rather poor form in most object modules.  In an
364       object module, you should set up a protective veil to separate
365       interface from implementation.  So provide a class method to access
366       class data just as you provide object methods to access object data.
367
368       So, you could still keep $Census as a package global and rely upon
369       others to honor the contract of the module and therefore not play
370       around with its implementation.  You could even be supertricky and make
371       $Census a tied object as described in perltie, thereby intercepting all
372       accesses.
373
374       But more often than not, you just want to make your class data a file-
375       scoped lexical.  To do so, simply put this at the top of the file:
376
377           my $Census = 0;
378
379       Even though the scope of a my() normally expires when the block in
380       which it was declared is done (in this case the whole file being
381       required or used), Perl's deep binding of lexical variables guarantees
382       that the variable will not be deallocated, remaining accessible to
383       functions declared within that scope.  This doesn't work with global
384       variables given temporary values via local(), though.
385
386       Irrespective of whether you leave $Census a package global or make it
387       instead a file-scoped lexical, you should make these changes to your
388       Person::new() constructor:
389
390           sub new {
391               my $class = shift;
392               my $self  = {};
393               $Census++;
394               $self->{NAME}   = undef;
395               $self->{AGE}    = undef;
396               $self->{PEERS}  = [];
397               bless ($self, $class);
398               return $self;
399           }
400
401           sub population {
402               return $Census;
403           }
404
405       Now that we've done this, we certainly do need a destructor so that
406       when Person is destroyed, the $Census goes down.  Here's how this could
407       be done:
408
409           sub DESTROY { --$Census }
410
411       Notice how there's no memory to deallocate in the destructor?  That's
412       something that Perl takes care of for you all by itself.
413
414       Alternatively, you could use the Class::Data::Inheritable module from
415       CPAN.
416
417   Accessing Class Data
418       It turns out that this is not really a good way to go about handling
419       class data.  A good scalable rule is that you must never reference
420       class data directly from an object method.  Otherwise you aren't
421       building a scalable, inheritable class.  The object must be the
422       rendezvous point for all operations, especially from an object method.
423       The globals (class data) would in some sense be in the "wrong" package
424       in your derived classes.  In Perl, methods execute in the context of
425       the class they were defined in, not that of the object that triggered
426       them.  Therefore, namespace visibility of package globals in methods is
427       unrelated to inheritance.
428
429       Got that?  Maybe not.  Ok, let's say that some other class "borrowed"
430       (well, inherited) the DESTROY method as it was defined above.  When
431       those objects are destroyed, the original $Census variable will be
432       altered, not the one in the new class's package namespace.  Perhaps
433       this is what you want, but probably it isn't.
434
435       Here's how to fix this.  We'll store a reference to the data in the
436       value accessed by the hash key "_CENSUS".  Why the underscore?  Well,
437       mostly because an initial underscore already conveys strong feelings of
438       magicalness to a C programmer.  It's really just a mnemonic device to
439       remind ourselves that this field is special and not to be used as a
440       public data member in the same way that NAME, AGE, and PEERS are.
441       (Because we've been developing this code under the strict pragma, prior
442       to perl version 5.004 we'll have to quote the field name.)
443
444           sub new {
445               my $class = shift;
446               my $self  = {};
447               $self->{NAME}     = undef;
448               $self->{AGE}      = undef;
449               $self->{PEERS}    = [];
450               # "private" data
451               $self->{"_CENSUS"} = \$Census;
452               bless ($self, $class);
453               ++ ${ $self->{"_CENSUS"} };
454               return $self;
455           }
456
457           sub population {
458               my $self = shift;
459               if (ref $self) {
460                   return ${ $self->{"_CENSUS"} };
461               } else {
462                   return $Census;
463               }
464           }
465
466           sub DESTROY {
467               my $self = shift;
468               -- ${ $self->{"_CENSUS"} };
469           }
470
471   Debugging Methods
472       It's common for a class to have a debugging mechanism.  For example,
473       you might want to see when objects are created or destroyed.  To do
474       that, add a debugging variable as a file-scoped lexical.  For this,
475       we'll pull in the standard Carp module to emit our warnings and fatal
476       messages.  That way messages will come out with the caller's filename
477       and line number instead of our own; if we wanted them to be from our
478       own perspective, we'd just use die() and warn() directly instead of
479       croak() and carp() respectively.
480
481           use Carp;
482           my $Debugging = 0;
483
484       Now add a new class method to access the variable.
485
486           sub debug {
487               my $class = shift;
488               if (ref $class)  { confess "Class method called as object method" }
489               unless (@_ == 1) { confess "usage: CLASSNAME->debug(level)" }
490               $Debugging = shift;
491           }
492
493       Now fix up DESTROY to murmur a bit as the moribund object expires:
494
495           sub DESTROY {
496               my $self = shift;
497               if ($Debugging) { carp "Destroying $self " . $self->name }
498               -- ${ $self->{"_CENSUS"} };
499           }
500
501       One could conceivably make a per-object debug state.  That way you
502       could call both of these:
503
504           Person->debug(1);   # entire class
505           $him->debug(1);     # just this object
506
507       To do so, we need our debugging method to be a "bimodal" one, one that
508       works on both classes and objects.  Therefore, adjust the debug() and
509       DESTROY methods as follows:
510
511           sub debug {
512               my $self = shift;
513               confess "usage: thing->debug(level)"    unless @_ == 1;
514               my $level = shift;
515               if (ref($self))  {
516                   $self->{"_DEBUG"} = $level;         # just myself
517               } else {
518                   $Debugging        = $level;         # whole class
519               }
520           }
521
522           sub DESTROY {
523               my $self = shift;
524               if ($Debugging || $self->{"_DEBUG"}) {
525                   carp "Destroying $self " . $self->name;
526               }
527               -- ${ $self->{"_CENSUS"} };
528           }
529
530       What happens if a derived class (which we'll call Employee) inherits
531       methods from this Person base class?  Then "Employee->debug()", when
532       called as a class method, manipulates $Person::Debugging not
533       $Employee::Debugging.
534
535   Class Destructors
536       The object destructor handles the death of each distinct object.  But
537       sometimes you want a bit of cleanup when the entire class is shut down,
538       which currently only happens when the program exits.  To make such a
539       class destructor, create a function in that class's package named END.
540       This works just like the END function in traditional modules, meaning
541       that it gets called whenever your program exits unless it execs or dies
542       of an uncaught signal.  For example,
543
544           sub END {
545               if ($Debugging) {
546                   print "All persons are going away now.\n";
547               }
548           }
549
550       When the program exits, all the class destructors (END functions) are
551       be called in the opposite order that they were loaded in (LIFO order).
552
553   Documenting the Interface
554       And there you have it: we've just shown you the implementation of this
555       Person class.  Its interface would be its documentation.  Usually this
556       means putting it in pod ("plain old documentation") format right there
557       in the same file.  In our Person example, we would place the following
558       docs anywhere in the Person.pm file.  Even though it looks mostly like
559       code, it's not.  It's embedded documentation such as would be used by
560       the pod2man, pod2html, or pod2text programs.  The Perl compiler ignores
561       pods entirely, just as the translators ignore code.  Here's an example
562       of some pods describing the informal interface:
563
564           =head1 NAME
565
566           Person - class to implement people
567
568           =head1 SYNOPSIS
569
570            use Person;
571
572            #################
573            # class methods #
574            #################
575            $ob    = Person->new;
576            $count = Person->population;
577
578            #######################
579            # object data methods #
580            #######################
581
582            ### get versions ###
583                $who   = $ob->name;
584                $years = $ob->age;
585                @pals  = $ob->peers;
586
587            ### set versions ###
588                $ob->name("Jason");
589                $ob->age(23);
590                $ob->peers( "Norbert", "Rhys", "Phineas" );
591
592            ########################
593            # other object methods #
594            ########################
595
596            $phrase = $ob->exclaim;
597            $ob->happy_birthday;
598
599           =head1 DESCRIPTION
600
601           The Person class implements dah dee dah dee dah....
602
603       That's all there is to the matter of interface versus implementation.
604       A programmer who opens up the module and plays around with all the
605       private little shiny bits that were safely locked up behind the
606       interface contract has voided the warranty, and you shouldn't worry
607       about their fate.
608

Aggregation

610       Suppose you later want to change the class to implement better names.
611       Perhaps you'd like to support both given names (called Christian names,
612       irrespective of one's religion) and family names (called surnames),
613       plus nicknames and titles.  If users of your Person class have been
614       properly accessing it through its documented interface, then you can
615       easily change the underlying implementation.  If they haven't, then
616       they lose and it's their fault for breaking the contract and voiding
617       their warranty.
618
619       To do this, we'll make another class, this one called Fullname.  What's
620       the Fullname class look like?  To answer that question, you have to
621       first figure out how you want to use it.  How about we use it this way:
622
623           $him = Person->new();
624           $him->fullname->title("St");
625           $him->fullname->christian("Thomas");
626           $him->fullname->surname("Aquinas");
627           $him->fullname->nickname("Tommy");
628           printf "His normal name is %s\n", $him->name;
629           printf "But his real name is %s\n", $him->fullname->as_string;
630
631       Ok.  To do this, we'll change Person::new() so that it supports a full
632       name field this way:
633
634           sub new {
635               my $class = shift;
636               my $self  = {};
637               $self->{FULLNAME} = Fullname->new();
638               $self->{AGE}      = undef;
639               $self->{PEERS}    = [];
640               $self->{"_CENSUS"} = \$Census;
641               bless ($self, $class);
642               ++ ${ $self->{"_CENSUS"} };
643               return $self;
644           }
645
646           sub fullname {
647               my $self = shift;
648               return $self->{FULLNAME};
649           }
650
651       Then to support old code, define Person::name() this way:
652
653           sub name {
654               my $self = shift;
655               return $self->{FULLNAME}->nickname(@_)
656                 ||   $self->{FULLNAME}->christian(@_);
657           }
658
659       Here's the Fullname class.  We'll use the same technique of using a
660       hash reference to hold data fields, and methods by the appropriate name
661       to access them:
662
663           package Fullname;
664           use strict;
665
666           sub new {
667               my $class = shift;
668               my $self  = {
669                   TITLE       => undef,
670                   CHRISTIAN   => undef,
671                   SURNAME     => undef,
672                   NICK        => undef,
673               };
674               bless ($self, $class);
675               return $self;
676           }
677
678           sub christian {
679               my $self = shift;
680               if (@_) { $self->{CHRISTIAN} = shift }
681               return $self->{CHRISTIAN};
682           }
683
684           sub surname {
685               my $self = shift;
686               if (@_) { $self->{SURNAME} = shift }
687               return $self->{SURNAME};
688           }
689
690           sub nickname {
691               my $self = shift;
692               if (@_) { $self->{NICK} = shift }
693               return $self->{NICK};
694           }
695
696           sub title {
697               my $self = shift;
698               if (@_) { $self->{TITLE} = shift }
699               return $self->{TITLE};
700           }
701
702           sub as_string {
703               my $self = shift;
704               my $name = join(" ", @$self{'CHRISTIAN', 'SURNAME'});
705               if ($self->{TITLE}) {
706                   $name = $self->{TITLE} . " " . $name;
707               }
708               return $name;
709           }
710
711           1;
712
713       Finally, here's the test program:
714
715           #!/usr/bin/perl -w
716           use strict;
717           use Person;
718           sub END { show_census() }
719
720           sub show_census ()  {
721               printf "Current population: %d\n", Person->population;
722           }
723
724           Person->debug(1);
725
726           show_census();
727
728           my $him = Person->new();
729
730           $him->fullname->christian("Thomas");
731           $him->fullname->surname("Aquinas");
732           $him->fullname->nickname("Tommy");
733           $him->fullname->title("St");
734           $him->age(1);
735
736           printf "%s is really %s.\n", $him->name, $him->fullname->as_string;
737           printf "%s's age: %d.\n", $him->name, $him->age;
738           $him->happy_birthday;
739           printf "%s's age: %d.\n", $him->name, $him->age;
740
741           show_census();
742

Inheritance

744       Object-oriented programming systems all support some notion of
745       inheritance.  Inheritance means allowing one class to piggy-back on top
746       of another one so you don't have to write the same code again and
747       again.  It's about software reuse, and therefore related to Laziness,
748       the principal virtue of a programmer.  (The import/export mechanisms in
749       traditional modules are also a form of code reuse, but a simpler one
750       than the true inheritance that you find in object modules.)
751
752       Sometimes the syntax of inheritance is built into the core of the
753       language, and sometimes it's not.  Perl has no special syntax for
754       specifying the class (or classes) to inherit from.  Instead, it's all
755       strictly in the semantics.  Each package can have a variable called
756       @ISA, which governs (method) inheritance.  If you try to call a method
757       on an object or class, and that method is not found in that object's
758       package, Perl then looks to @ISA for other packages to go looking
759       through in search of the missing method.
760
761       Like the special per-package variables recognized by Exporter (such as
762       @EXPORT, @EXPORT_OK, @EXPORT_FAIL, %EXPORT_TAGS, and $VERSION), the
763       @ISA array must be a package-scoped global and not a file-scoped
764       lexical created via my().  Most classes have just one item in their
765       @ISA array.  In this case, we have what's called "single inheritance",
766       or SI for short.
767
768       Consider this class:
769
770           package Employee;
771           use Person;
772           @ISA = ("Person");
773           1;
774
775       Not a lot to it, eh?  All it's doing so far is loading in another class
776       and stating that this one will inherit methods from that other class if
777       need be.  We have given it none of its own methods.  We rely upon an
778       Employee to behave just like a Person.
779
780       Setting up an empty class like this is called the "empty subclass
781       test"; that is, making a derived class that does nothing but inherit
782       from a base class.  If the original base class has been designed
783       properly, then the new derived class can be used as a drop-in
784       replacement for the old one.  This means you should be able to write a
785       program like this:
786
787           use Employee;
788           my $empl = Employee->new();
789           $empl->name("Jason");
790           $empl->age(23);
791           printf "%s is age %d.\n", $empl->name, $empl->age;
792
793       By proper design, we mean always using the two-argument form of
794       bless(), avoiding direct access of global data, and not exporting
795       anything.  If you look back at the Person::new() function we defined
796       above, we were careful to do that.  There's a bit of package data used
797       in the constructor, but the reference to this is stored on the object
798       itself and all other methods access package data via that reference, so
799       we should be ok.
800
801       What do we mean by the Person::new() function -- isn't that actually a
802       method?  Well, in principle, yes.  A method is just a function that
803       expects as its first argument a class name (package) or object (blessed
804       reference).   Person::new() is the function that both the
805       "Person->new()" method and the "Employee->new()" method end up calling.
806       Understand that while a method call looks a lot like a function call,
807       they aren't really quite the same, and if you treat them as the same,
808       you'll very soon be left with nothing but broken programs.  First, the
809       actual underlying calling conventions are different: method calls get
810       an extra argument.  Second, function calls don't do inheritance, but
811       methods do.
812
813               Method Call             Resulting Function Call
814               -----------             ------------------------
815               Person->new()           Person::new("Person")
816               Employee->new()         Person::new("Employee")
817
818       So don't use function calls when you mean to call a method.
819
820       If an employee is just a Person, that's not all too very interesting.
821       So let's add some other methods.  We'll give our employee data fields
822       to access their salary, their employee ID, and their start date.
823
824       If you're getting a little tired of creating all these nearly identical
825       methods just to get at the object's data, do not despair.  Later, we'll
826       describe several different convenience mechanisms for shortening this
827       up.  Meanwhile, here's the straight-forward way:
828
829           sub salary {
830               my $self = shift;
831               if (@_) { $self->{SALARY} = shift }
832               return $self->{SALARY};
833           }
834
835           sub id_number {
836               my $self = shift;
837               if (@_) { $self->{ID} = shift }
838               return $self->{ID};
839           }
840
841           sub start_date {
842               my $self = shift;
843               if (@_) { $self->{START_DATE} = shift }
844               return $self->{START_DATE};
845           }
846
847   Overridden Methods
848       What happens when both a derived class and its base class have the same
849       method defined?  Well, then you get the derived class's version of that
850       method.  For example, let's say that we want the peers() method called
851       on an employee to act a bit differently.  Instead of just returning the
852       list of peer names, let's return slightly different strings.  So doing
853       this:
854
855           $empl->peers("Peter", "Paul", "Mary");
856           printf "His peers are: %s\n", join(", ", $empl->peers);
857
858       will produce:
859
860           His peers are: PEON=PETER, PEON=PAUL, PEON=MARY
861
862       To do this, merely add this definition into the Employee.pm file:
863
864           sub peers {
865               my $self = shift;
866               if (@_) { @{ $self->{PEERS} } = @_ }
867               return map { "PEON=\U$_" } @{ $self->{PEERS} };
868           }
869
870       There, we've just demonstrated the high-falutin' concept known in
871       certain circles as polymorphism.  We've taken on the form and behaviour
872       of an existing object, and then we've altered it to suit our own
873       purposes.  This is a form of Laziness.  (Getting polymorphed is also
874       what happens when the wizard decides you'd look better as a frog.)
875
876       Every now and then you'll want to have a method call trigger both its
877       derived class (also known as "subclass") version as well as its base
878       class (also known as "superclass") version.  In practice, constructors
879       and destructors are likely to want to do this, and it probably also
880       makes sense in the debug() method we showed previously.
881
882       To do this, add this to Employee.pm:
883
884           use Carp;
885           my $Debugging = 0;
886
887           sub debug {
888               my $self = shift;
889               confess "usage: thing->debug(level)"    unless @_ == 1;
890               my $level = shift;
891               if (ref($self))  {
892                   $self->{"_DEBUG"} = $level;
893               } else {
894                   $Debugging = $level;            # whole class
895               }
896               Person::debug($self, $Debugging);   # don't really do this
897           }
898
899       As you see, we turn around and call the Person package's debug()
900       function.  But this is far too fragile for good design.  What if Person
901       doesn't have a debug() function, but is inheriting its debug() method
902       from elsewhere?  It would have been slightly better to say
903
904           Person->debug($Debugging);
905
906       But even that's got too much hard-coded.  It's somewhat better to say
907
908           $self->Person::debug($Debugging);
909
910       Which is a funny way to say to start looking for a debug() method up in
911       Person.  This strategy is more often seen on overridden object methods
912       than on overridden class methods.
913
914       There is still something a bit off here.  We've hard-coded our
915       superclass's name.  This in particular is bad if you change which
916       classes you inherit from, or add others.  Fortunately, the pseudoclass
917       SUPER comes to the rescue here.
918
919           $self->SUPER::debug($Debugging);
920
921       This way it starts looking in my class's @ISA.  This only makes sense
922       from within a method call, though.  Don't try to access anything in
923       SUPER:: from anywhere else, because it doesn't exist outside an
924       overridden method call. Note that "SUPER" refers to the superclass of
925       the current package, not to the superclass of $self.
926
927       Things are getting a bit complicated here.  Have we done anything we
928       shouldn't?  As before, one way to test whether we're designing a decent
929       class is via the empty subclass test.  Since we already have an
930       Employee class that we're trying to check, we'd better get a new empty
931       subclass that can derive from Employee.  Here's one:
932
933           package Boss;
934           use Employee;        # :-)
935           @ISA = qw(Employee);
936
937       And here's the test program:
938
939           #!/usr/bin/perl -w
940           use strict;
941           use Boss;
942           Boss->debug(1);
943
944           my $boss = Boss->new();
945
946           $boss->fullname->title("Don");
947           $boss->fullname->surname("Pichon Alvarez");
948           $boss->fullname->christian("Federico Jesus");
949           $boss->fullname->nickname("Fred");
950
951           $boss->age(47);
952           $boss->peers("Frank", "Felipe", "Faust");
953
954           printf "%s is age %d.\n", $boss->fullname->as_string, $boss->age;
955           printf "His peers are: %s\n", join(", ", $boss->peers);
956
957       Running it, we see that we're still ok.  If you'd like to dump out your
958       object in a nice format, somewhat like the way the 'x' command works in
959       the debugger, you could use the Data::Dumper module from CPAN this way:
960
961           use Data::Dumper;
962           print "Here's the boss:\n";
963           print Dumper($boss);
964
965       Which shows us something like this:
966
967           Here's the boss:
968           $VAR1 = bless( {
969                _CENSUS => \1,
970                FULLNAME => bless( {
971                                     TITLE => 'Don',
972                                     SURNAME => 'Pichon Alvarez',
973                                     NICK => 'Fred',
974                                     CHRISTIAN => 'Federico Jesus'
975                                   }, 'Fullname' ),
976                AGE => 47,
977                PEERS => [
978                           'Frank',
979                           'Felipe',
980                           'Faust'
981                         ]
982              }, 'Boss' );
983
984       Hm.... something's missing there.  What about the salary, start date,
985       and ID fields?  Well, we never set them to anything, even undef, so
986       they don't show up in the hash's keys.  The Employee class has no new()
987       method of its own, and the new() method in Person doesn't know about
988       Employees.  (Nor should it: proper OO design dictates that a subclass
989       be allowed to know about its immediate superclass, but never vice-
990       versa.)  So let's fix up Employee::new() this way:
991
992           sub new {
993               my $class = shift;
994               my $self  = $class->SUPER::new();
995               $self->{SALARY}        = undef;
996               $self->{ID}            = undef;
997               $self->{START_DATE}    = undef;
998               bless ($self, $class);          # reconsecrate
999               return $self;
1000           }
1001
1002       Now if you dump out an Employee or Boss object, you'll find that new
1003       fields show up there now.
1004
1005   Multiple Inheritance
1006       Ok, at the risk of confusing beginners and annoying OO gurus, it's time
1007       to confess that Perl's object system includes that controversial notion
1008       known as multiple inheritance, or MI for short.  All this means is that
1009       rather than having just one parent class who in turn might itself have
1010       a parent class, etc., that you can directly inherit from two or more
1011       parents.  It's true that some uses of MI can get you into trouble,
1012       although hopefully not quite so much trouble with Perl as with
1013       dubiously-OO languages like C++.
1014
1015       The way it works is actually pretty simple: just put more than one
1016       package name in your @ISA array.  When it comes time for Perl to go
1017       finding methods for your object, it looks at each of these packages in
1018       order.  Well, kinda.  It's actually a fully recursive, depth-first
1019       order by default (see mro for alternate method resolution orders).
1020       Consider a bunch of @ISA arrays like this:
1021
1022           @First::ISA    = qw( Alpha );
1023           @Second::ISA   = qw( Beta );
1024           @Third::ISA    = qw( First Second );
1025
1026       If you have an object of class Third:
1027
1028           my $ob = Third->new();
1029           $ob->spin();
1030
1031       How do we find a spin() method (or a new() method for that matter)?
1032       Because the search is depth-first, classes will be looked up in the
1033       following order: Third, First, Alpha, Second, and Beta.
1034
1035       In practice, few class modules have been seen that actually make use of
1036       MI.  One nearly always chooses simple containership of one class within
1037       another over MI.  That's why our Person object contained a Fullname
1038       object.  That doesn't mean it was one.
1039
1040       However, there is one particular area where MI in Perl is rampant:
1041       borrowing another class's class methods.  This is rather common,
1042       especially with some bundled "objectless" classes, like Exporter,
1043       DynaLoader, AutoLoader, and SelfLoader.  These classes do not provide
1044       constructors; they exist only so you may inherit their class methods.
1045       (It's not entirely clear why inheritance was done here rather than
1046       traditional module importation.)
1047
1048       For example, here is the POSIX module's @ISA:
1049
1050           package POSIX;
1051           @ISA = qw(Exporter DynaLoader);
1052
1053       The POSIX module isn't really an object module, but then, neither are
1054       Exporter or DynaLoader.  They're just lending their classes' behaviours
1055       to POSIX.
1056
1057       Why don't people use MI for object methods much?  One reason is that it
1058       can have complicated side-effects.  For one thing, your inheritance
1059       graph (no longer a tree) might converge back to the same base class.
1060       Although Perl guards against recursive inheritance, merely having
1061       parents who are related to each other via a common ancestor, incestuous
1062       though it sounds, is not forbidden.  What if in our Third class shown
1063       above we wanted its new() method to also call both overridden
1064       constructors in its two parent classes?  The SUPER notation would only
1065       find the first one.  Also, what about if the Alpha and Beta classes
1066       both had a common ancestor, like Nought?  If you kept climbing up the
1067       inheritance tree calling overridden methods, you'd end up calling
1068       Nought::new() twice, which might well be a bad idea.
1069
1070   UNIVERSAL: The Root of All Objects
1071       Wouldn't it be convenient if all objects were rooted at some ultimate
1072       base class?  That way you could give every object common methods
1073       without having to go and add it to each and every @ISA.  Well, it turns
1074       out that you can.  You don't see it, but Perl tacitly and irrevocably
1075       assumes that there's an extra element at the end of @ISA: the class
1076       UNIVERSAL.  In version 5.003, there were no predefined methods there,
1077       but you could put whatever you felt like into it.
1078
1079       However, as of version 5.004 (or some subversive releases, like
1080       5.003_08), UNIVERSAL has some methods in it already.  These are builtin
1081       to your Perl binary, so they don't take any extra time to load.
1082       Predefined methods include isa(), can(), and VERSION().  isa() tells
1083       you whether an object or class "is" another one without having to
1084       traverse the hierarchy yourself:
1085
1086          $has_io = $fd->isa("IO::Handle");
1087          $itza_handle = IO::Socket->isa("IO::Handle");
1088
1089       The can() method, called against that object or class, reports back
1090       whether its string argument is a callable method name in that class.
1091       In fact, it gives you back a function reference to that method:
1092
1093          $his_print_method = $obj->can('as_string');
1094
1095       Finally, the VERSION method checks whether the class (or the object's
1096       class) has a package global called $VERSION that's high enough, as in:
1097
1098           Some_Module->VERSION(3.0);
1099           $his_vers = $ob->VERSION();
1100
1101       However, we don't usually call VERSION ourselves.  (Remember that an
1102       all uppercase function name is a Perl convention that indicates that
1103       the function will be automatically used by Perl in some way.)  In this
1104       case, it happens when you say
1105
1106           use Some_Module 3.0;
1107
1108       If you wanted to add version checking to your Person class explained
1109       above, just add this to Person.pm:
1110
1111           our $VERSION = '1.1';
1112
1113       and then in Employee.pm you can say
1114
1115           use Person 1.1;
1116
1117       And it would make sure that you have at least that version number or
1118       higher available.   This is not the same as loading in that exact
1119       version number.  No mechanism currently exists for concurrent
1120       installation of multiple versions of a module.  Lamentably.
1121
1122   Deeper UNIVERSAL details
1123       It is also valid (though perhaps unwise in most cases) to put other
1124       packages' names in @UNIVERSAL::ISA.  These packages will also be
1125       implicitly inherited by all classes, just as UNIVERSAL itself is.
1126       However, neither UNIVERSAL nor any of its parents from the @ISA tree
1127       are explicit base classes of all objects.  To clarify, given the
1128       following:
1129
1130           @UNIVERSAL::ISA = ('REALLYUNIVERSAL');
1131
1132           package REALLYUNIVERSAL;
1133           sub special_method { return "123" }
1134
1135           package Foo;
1136           sub normal_method { return "321" }
1137
1138       Calling Foo->special_method() will return "123", but calling
1139       Foo->isa('REALLYUNIVERSAL') or Foo->isa('UNIVERSAL') will return false.
1140
1141       If your class is using an alternate mro like C3 (see mro), method
1142       resolution within UNIVERSAL / @UNIVERSAL::ISA will still occur in the
1143       default depth-first left-to-right manner, after the class's C3 mro is
1144       exhausted.
1145
1146       All of the above is made more intuitive by realizing what really
1147       happens during method lookup, which is roughly like this ugly pseudo-
1148       code:
1149
1150           get_mro(class) {
1151               # recurses down the @ISA's starting at class,
1152               # builds a single linear array of all
1153               # classes to search in the appropriate order.
1154               # The method resolution order (mro) to use
1155               # for the ordering is whichever mro "class"
1156               # has set on it (either default (depth first
1157               # l-to-r) or C3 ordering).
1158               # The first entry in the list is the class
1159               # itself.
1160           }
1161
1162           find_method(class, methname) {
1163               foreach $class (get_mro(class)) {
1164                   if($class->has_method(methname)) {
1165                       return ref_to($class->$methname);
1166                   }
1167               }
1168               foreach $class (get_mro(UNIVERSAL)) {
1169                   if($class->has_method(methname)) {
1170                       return ref_to($class->$methname);
1171                   }
1172               }
1173               return undef;
1174           }
1175
1176       However the code that implements UNIVERSAL::isa does not search in
1177       UNIVERSAL itself, only in the package's actual @ISA.
1178

Alternate Object Representations

1180       Nothing requires objects to be implemented as hash references.  An
1181       object can be any sort of reference so long as its referent has been
1182       suitably blessed.  That means scalar, array, and code references are
1183       also fair game.
1184
1185       A scalar would work if the object has only one datum to hold.  An array
1186       would work for most cases, but makes inheritance a bit dodgy because
1187       you have to invent new indices for the derived classes.
1188
1189   Arrays as Objects
1190       If the user of your class honors the contract and sticks to the
1191       advertised interface, then you can change its underlying interface if
1192       you feel like it.  Here's another implementation that conforms to the
1193       same interface specification.  This time we'll use an array reference
1194       instead of a hash reference to represent the object.
1195
1196           package Person;
1197           use strict;
1198
1199           my($NAME, $AGE, $PEERS) = ( 0 .. 2 );
1200
1201           ############################################
1202           ## the object constructor (array version) ##
1203           ############################################
1204           sub new {
1205               my $self = [];
1206               $self->[$NAME]   = undef;  # this is unnecessary
1207               $self->[$AGE]    = undef;  # as is this
1208               $self->[$PEERS]  = [];     # but this isn't, really
1209               bless($self);
1210               return $self;
1211           }
1212
1213           sub name {
1214               my $self = shift;
1215               if (@_) { $self->[$NAME] = shift }
1216               return $self->[$NAME];
1217           }
1218
1219           sub age {
1220               my $self = shift;
1221               if (@_) { $self->[$AGE] = shift }
1222               return $self->[$AGE];
1223           }
1224
1225           sub peers {
1226               my $self = shift;
1227               if (@_) { @{ $self->[$PEERS] } = @_ }
1228               return @{ $self->[$PEERS] };
1229           }
1230
1231           1;  # so the require or use succeeds
1232
1233       You might guess that the array access would be a lot faster than the
1234       hash access, but they're actually comparable.  The array is a little
1235       bit faster, but not more than ten or fifteen percent, even when you
1236       replace the variables above like $AGE with literal numbers, like 1.  A
1237       bigger difference between the two approaches can be found in memory
1238       use.  A hash representation takes up more memory than an array
1239       representation because you have to allocate memory for the keys as well
1240       as for the values.  However, it really isn't that bad, especially since
1241       as of version 5.004, memory is only allocated once for a given hash
1242       key, no matter how many hashes have that key.  It's expected that
1243       sometime in the future, even these differences will fade into obscurity
1244       as more efficient underlying representations are devised.
1245
1246       Still, the tiny edge in speed (and somewhat larger one in memory) is
1247       enough to make some programmers choose an array representation for
1248       simple classes.  There's still a little problem with scalability,
1249       though, because later in life when you feel like creating subclasses,
1250       you'll find that hashes just work out better.
1251
1252   Closures as Objects
1253       Using a code reference to represent an object offers some fascinating
1254       possibilities.  We can create a new anonymous function (closure) who
1255       alone in all the world can see the object's data.  This is because we
1256       put the data into an anonymous hash that's lexically visible only to
1257       the closure we create, bless, and return as the object.  This object's
1258       methods turn around and call the closure as a regular subroutine call,
1259       passing it the field we want to affect.  (Yes, the double-function call
1260       is slow, but if you wanted fast, you wouldn't be using objects at all,
1261       eh? :-)
1262
1263       Use would be similar to before:
1264
1265           use Person;
1266           $him = Person->new();
1267           $him->name("Jason");
1268           $him->age(23);
1269           $him->peers( [ "Norbert", "Rhys", "Phineas" ] );
1270           printf "%s is %d years old.\n", $him->name, $him->age;
1271           print "His peers are: ", join(", ", @{$him->peers}), "\n";
1272
1273       but the implementation would be radically, perhaps even sublimely
1274       different:
1275
1276           package Person;
1277
1278           sub new {
1279                my $class  = shift;
1280                my $self = {
1281                   NAME  => undef,
1282                   AGE   => undef,
1283                   PEERS => [],
1284                };
1285                my $closure = sub {
1286                   my $field = shift;
1287                   if (@_) { $self->{$field} = shift }
1288                   return    $self->{$field};
1289               };
1290               bless($closure, $class);
1291               return $closure;
1292           }
1293
1294           sub name   { &{ $_[0] }("NAME",  @_[ 1 .. $#_ ] ) }
1295           sub age    { &{ $_[0] }("AGE",   @_[ 1 .. $#_ ] ) }
1296           sub peers  { &{ $_[0] }("PEERS", @_[ 1 .. $#_ ] ) }
1297
1298           1;
1299
1300       Because this object is hidden behind a code reference, it's probably a
1301       bit mysterious to those whose background is more firmly rooted in
1302       standard procedural or object-based programming languages than in
1303       functional programming languages whence closures derive.  The object
1304       created and returned by the new() method is itself not a data reference
1305       as we've seen before.  It's an anonymous code reference that has within
1306       it access to a specific version (lexical binding and instantiation) of
1307       the object's data, which are stored in the private variable $self.
1308       Although this is the same function each time, it contains a different
1309       version of $self.
1310
1311       When a method like "$him->name("Jason")" is called, its implicit zeroth
1312       argument is the invoking object--just as it is with all method calls.
1313       But in this case, it's our code reference (something like a function
1314       pointer in C++, but with deep binding of lexical variables).  There's
1315       not a lot to be done with a code reference beyond calling it, so that's
1316       just what we do when we say "&{$_[0]}".  This is just a regular
1317       function call, not a method call.  The initial argument is the string
1318       "NAME", and any remaining arguments are whatever had been passed to the
1319       method itself.
1320
1321       Once we're executing inside the closure that had been created in new(),
1322       the $self hash reference suddenly becomes visible.  The closure grabs
1323       its first argument ("NAME" in this case because that's what the name()
1324       method passed it), and uses that string to subscript into the private
1325       hash hidden in its unique version of $self.
1326
1327       Nothing under the sun will allow anyone outside the executing method to
1328       be able to get at this hidden data.  Well, nearly nothing.  You could
1329       single step through the program using the debugger and find out the
1330       pieces while you're in the method, but everyone else is out of luck.
1331
1332       There, if that doesn't excite the Scheme folks, then I just don't know
1333       what will.  Translation of this technique into C++, Java, or any other
1334       braindead-static language is left as a futile exercise for aficionados
1335       of those camps.
1336
1337       You could even add a bit of nosiness via the caller() function and make
1338       the closure refuse to operate unless called via its own package.  This
1339       would no doubt satisfy certain fastidious concerns of programming
1340       police and related puritans.
1341
1342       If you were wondering when Hubris, the third principle virtue of a
1343       programmer, would come into play, here you have it. (More seriously,
1344       Hubris is just the pride in craftsmanship that comes from having
1345       written a sound bit of well-designed code.)
1346

AUTOLOAD: Proxy Methods

1348       Autoloading is a way to intercept calls to undefined methods.  An
1349       autoload routine may choose to create a new function on the fly, either
1350       loaded from disk or perhaps just eval()ed right there.  This define-on-
1351       the-fly strategy is why it's called autoloading.
1352
1353       But that's only one possible approach.  Another one is to just have the
1354       autoloaded method itself directly provide the requested service.  When
1355       used in this way, you may think of autoloaded methods as "proxy"
1356       methods.
1357
1358       When Perl tries to call an undefined function in a particular package
1359       and that function is not defined, it looks for a function in that same
1360       package called AUTOLOAD.  If one exists, it's called with the same
1361       arguments as the original function would have had.  The fully-qualified
1362       name of the function is stored in that package's global variable
1363       $AUTOLOAD.  Once called, the function can do anything it would like,
1364       including defining a new function by the right name, and then doing a
1365       really fancy kind of "goto" right to it, erasing itself from the call
1366       stack.
1367
1368       What does this have to do with objects?  After all, we keep talking
1369       about functions, not methods.  Well, since a method is just a function
1370       with an extra argument and some fancier semantics about where it's
1371       found, we can use autoloading for methods, too.  Perl doesn't start
1372       looking for an AUTOLOAD method until it has exhausted the recursive
1373       hunt up through @ISA, though.  Some programmers have even been known to
1374       define a UNIVERSAL::AUTOLOAD method to trap unresolved method calls to
1375       any kind of object.
1376
1377   Autoloaded Data Methods
1378       You probably began to get a little suspicious about the duplicated code
1379       way back earlier when we first showed you the Person class, and then
1380       later the Employee class.  Each method used to access the hash fields
1381       looked virtually identical.  This should have tickled that great
1382       programming virtue, Impatience, but for the time, we let Laziness win
1383       out, and so did nothing.  Proxy methods can cure this.
1384
1385       Instead of writing a new function every time we want a new data field,
1386       we'll use the autoload mechanism to generate (actually, mimic) methods
1387       on the fly.  To verify that we're accessing a valid member, we will
1388       check against an "_permitted" (pronounced "under-permitted") field,
1389       which is a reference to a file-scoped lexical (like a C file static)
1390       hash of permitted fields in this record called %fields.  Why the
1391       underscore?  For the same reason as the _CENSUS field we once used: as
1392       a marker that means "for internal use only".
1393
1394       Here's what the module initialization code and class constructor will
1395       look like when taking this approach:
1396
1397           package Person;
1398           use Carp;
1399           our $AUTOLOAD;  # it's a package global
1400
1401           my %fields = (
1402               name        => undef,
1403               age         => undef,
1404               peers       => undef,
1405           );
1406
1407           sub new {
1408               my $class = shift;
1409               my $self  = {
1410                   _permitted => \%fields,
1411                   %fields,
1412               };
1413               bless $self, $class;
1414               return $self;
1415           }
1416
1417       If we wanted our record to have default values, we could fill those in
1418       where current we have "undef" in the %fields hash.
1419
1420       Notice how we saved a reference to our class data on the object itself?
1421       Remember that it's important to access class data through the object
1422       itself instead of having any method reference %fields directly, or else
1423       you won't have a decent inheritance.
1424
1425       The real magic, though, is going to reside in our proxy method, which
1426       will handle all calls to undefined methods for objects of class Person
1427       (or subclasses of Person).  It has to be called AUTOLOAD.  Again, it's
1428       all caps because it's called for us implicitly by Perl itself, not by a
1429       user directly.
1430
1431           sub AUTOLOAD {
1432               my $self = shift;
1433               my $type = ref($self)
1434                           or croak "$self is not an object";
1435
1436               my $name = $AUTOLOAD;
1437               $name =~ s/.*://;   # strip fully-qualified portion
1438
1439               unless (exists $self->{_permitted}->{$name} ) {
1440                   croak "Can't access `$name' field in class $type";
1441               }
1442
1443               if (@_) {
1444                   return $self->{$name} = shift;
1445               } else {
1446                   return $self->{$name};
1447               }
1448           }
1449
1450       Pretty nifty, eh?  All we have to do to add new data fields is modify
1451       %fields.  No new functions need be written.
1452
1453       I could have avoided the "_permitted" field entirely, but I wanted to
1454       demonstrate how to store a reference to class data on the object so you
1455       wouldn't have to access that class data directly from an object method.
1456
1457   Inherited Autoloaded Data Methods
1458       But what about inheritance?  Can we define our Employee class
1459       similarly?  Yes, so long as we're careful enough.
1460
1461       Here's how to be careful:
1462
1463           package Employee;
1464           use Person;
1465           use strict;
1466           our @ISA = qw(Person);
1467
1468           my %fields = (
1469               id          => undef,
1470               salary      => undef,
1471           );
1472
1473           sub new {
1474               my $class = shift;
1475               my $self  = $class->SUPER::new();
1476               my($element);
1477               foreach $element (keys %fields) {
1478                   $self->{_permitted}->{$element} = $fields{$element};
1479               }
1480               @{$self}{keys %fields} = values %fields;
1481               return $self;
1482           }
1483
1484       Once we've done this, we don't even need to have an AUTOLOAD function
1485       in the Employee package, because we'll grab Person's version of that
1486       via inheritance, and it will all work out just fine.
1487

Metaclassical Tools

1489       Even though proxy methods can provide a more convenient approach to
1490       making more struct-like classes than tediously coding up data methods
1491       as functions, it still leaves a bit to be desired.  For one thing, it
1492       means you have to handle bogus calls that you don't mean to trap via
1493       your proxy.  It also means you have to be quite careful when dealing
1494       with inheritance, as detailed above.
1495
1496       Perl programmers have responded to this by creating several different
1497       class construction classes.  These metaclasses are classes that create
1498       other classes.  A couple worth looking at are Class::Struct and Alias.
1499       These and other related metaclasses can be found in the modules
1500       directory on CPAN.
1501
1502   Class::Struct
1503       One of the older ones is Class::Struct.  In fact, its syntax and
1504       interface were sketched out long before perl5 even solidified into a
1505       real thing.  What it does is provide you a way to "declare" a class as
1506       having objects whose fields are of a specific type.  The function that
1507       does this is called, not surprisingly enough, struct().  Because
1508       structures or records are not base types in Perl, each time you want to
1509       create a class to provide a record-like data object, you yourself have
1510       to define a new() method, plus separate data-access methods for each of
1511       that record's fields.  You'll quickly become bored with this process.
1512       The Class::Struct::struct() function alleviates this tedium.
1513
1514       Here's a simple example of using it:
1515
1516           use Class::Struct qw(struct);
1517           use Jobbie;  # user-defined; see below
1518
1519           struct 'Fred' => {
1520               one        => '$',
1521               many       => '@',
1522               profession => 'Jobbie',  # does not call Jobbie->new()
1523           };
1524
1525           $ob = Fred->new(profession => Jobbie->new());
1526           $ob->one("hmmmm");
1527
1528           $ob->many(0, "here");
1529           $ob->many(1, "you");
1530           $ob->many(2, "go");
1531           print "Just set: ", $ob->many(2), "\n";
1532
1533           $ob->profession->salary(10_000);
1534
1535       You can declare types in the struct to be basic Perl types, or user-
1536       defined types (classes).  User types will be initialized by calling
1537       that class's new() method.
1538
1539       Take care that the "Jobbie" object is not created automatically by the
1540       "Fred" class's new() method, so you should specify a "Jobbie" object
1541       when you create an instance of "Fred".
1542
1543       Here's a real-world example of using struct generation.  Let's say you
1544       wanted to override Perl's idea of gethostbyname() and gethostbyaddr()
1545       so that they would return objects that acted like C structures.  We
1546       don't care about high-falutin' OO gunk.  All we want is for these
1547       objects to act like structs in the C sense.
1548
1549           use Socket;
1550           use Net::hostent;
1551           $h = gethostbyname("perl.com");  # object return
1552           printf "perl.com's real name is %s, address %s\n",
1553               $h->name, inet_ntoa($h->addr);
1554
1555       Here's how to do this using the Class::Struct module.  The crux is
1556       going to be this call:
1557
1558           struct 'Net::hostent' => [          # note bracket
1559               name       => '$',
1560               aliases    => '@',
1561               addrtype   => '$',
1562               'length'   => '$',
1563               addr_list  => '@',
1564            ];
1565
1566       Which creates object methods of those names and types.  It even creates
1567       a new() method for us.
1568
1569       We could also have implemented our object this way:
1570
1571           struct 'Net::hostent' => {          # note brace
1572               name       => '$',
1573               aliases    => '@',
1574               addrtype   => '$',
1575               'length'   => '$',
1576               addr_list  => '@',
1577            };
1578
1579       and then Class::Struct would have used an anonymous hash as the object
1580       type, instead of an anonymous array.  The array is faster and smaller,
1581       but the hash works out better if you eventually want to do inheritance.
1582       Since for this struct-like object we aren't planning on inheritance,
1583       this time we'll opt for better speed and size over better flexibility.
1584
1585       Here's the whole implementation:
1586
1587           package Net::hostent;
1588           use strict;
1589
1590           BEGIN {
1591               use Exporter   ();
1592               our @EXPORT      = qw(gethostbyname gethostbyaddr gethost);
1593               our @EXPORT_OK   = qw(
1594                                      $h_name         @h_aliases
1595                                      $h_addrtype     $h_length
1596                                      @h_addr_list    $h_addr
1597                                  );
1598               our %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
1599           }
1600           our @EXPORT_OK;
1601
1602           # Class::Struct forbids use of @ISA
1603           sub import { goto &Exporter::import }
1604
1605           use Class::Struct qw(struct);
1606           struct 'Net::hostent' => [
1607              name        => '$',
1608              aliases     => '@',
1609              addrtype    => '$',
1610              'length'    => '$',
1611              addr_list   => '@',
1612           ];
1613
1614           sub addr { shift->addr_list->[0] }
1615
1616           sub populate (@) {
1617               return unless @_;
1618               my $hob = new();  # Class::Struct made this!
1619               $h_name     =    $hob->[0]              = $_[0];
1620               @h_aliases  = @{ $hob->[1] } = split ' ', $_[1];
1621               $h_addrtype =    $hob->[2]              = $_[2];
1622               $h_length   =    $hob->[3]              = $_[3];
1623               $h_addr     =                             $_[4];
1624               @h_addr_list = @{ $hob->[4] } =         @_[ (4 .. $#_) ];
1625               return $hob;
1626           }
1627
1628           sub gethostbyname ($)  { populate(CORE::gethostbyname(shift)) }
1629
1630           sub gethostbyaddr ($;$) {
1631               my ($addr, $addrtype);
1632               $addr = shift;
1633               require Socket unless @_;
1634               $addrtype = @_ ? shift : Socket::AF_INET();
1635               populate(CORE::gethostbyaddr($addr, $addrtype))
1636           }
1637
1638           sub gethost($) {
1639               if ($_[0] =~ /^\d+(?:\.\d+(?:\.\d+(?:\.\d+)?)?)?$/) {
1640                  require Socket;
1641                  &gethostbyaddr(Socket::inet_aton(shift));
1642               } else {
1643                  &gethostbyname;
1644               }
1645           }
1646
1647           1;
1648
1649       We've snuck in quite a fair bit of other concepts besides just dynamic
1650       class creation, like overriding core functions, import/export bits,
1651       function prototyping, short-cut function call via &whatever, and
1652       function replacement with "goto &whatever".  These all mostly make
1653       sense from the perspective of a traditional module, but as you can see,
1654       we can also use them in an object module.
1655
1656       You can look at other object-based, struct-like overrides of core
1657       functions in the 5.004 release of Perl in File::stat, Net::hostent,
1658       Net::netent, Net::protoent, Net::servent, Time::gmtime,
1659       Time::localtime, User::grent, and User::pwent.  These modules have a
1660       final component that's all lowercase, by convention reserved for
1661       compiler pragmas, because they affect the compilation and change a
1662       builtin function.  They also have the type names that a C programmer
1663       would most expect.
1664
1665   Data Members as Variables
1666       If you're used to C++ objects, then you're accustomed to being able to
1667       get at an object's data members as simple variables from within a
1668       method.  The Alias module provides for this, as well as a good bit
1669       more, such as the possibility of private methods that the object can
1670       call but folks outside the class cannot.
1671
1672       Here's an example of creating a Person using the Alias module.  When
1673       you update these magical instance variables, you automatically update
1674       value fields in the hash.  Convenient, eh?
1675
1676           package Person;
1677
1678           # this is the same as before...
1679           sub new {
1680                my $class = shift;
1681                my $self = {
1682                   NAME  => undef,
1683                   AGE   => undef,
1684                   PEERS => [],
1685               };
1686               bless($self, $class);
1687               return $self;
1688           }
1689
1690           use Alias qw(attr);
1691           our ($NAME, $AGE, $PEERS);
1692
1693           sub name {
1694               my $self = attr shift;
1695               if (@_) { $NAME = shift; }
1696               return    $NAME;
1697           }
1698
1699           sub age {
1700               my $self = attr shift;
1701               if (@_) { $AGE = shift; }
1702               return    $AGE;
1703           }
1704
1705           sub peers {
1706               my $self = attr shift;
1707               if (@_) { @PEERS = @_; }
1708               return    @PEERS;
1709           }
1710
1711           sub exclaim {
1712               my $self = attr shift;
1713               return sprintf "Hi, I'm %s, age %d, working with %s",
1714                   $NAME, $AGE, join(", ", @PEERS);
1715           }
1716
1717           sub happy_birthday {
1718               my $self = attr shift;
1719               return ++$AGE;
1720           }
1721
1722       The need for the "our" declaration is because what Alias does is play
1723       with package globals with the same name as the fields.  To use globals
1724       while "use strict" is in effect, you have to predeclare them.  These
1725       package variables are localized to the block enclosing the attr() call
1726       just as if you'd used a local() on them.  However, that means that
1727       they're still considered global variables with temporary values, just
1728       as with any other local().
1729
1730       It would be nice to combine Alias with something like Class::Struct or
1731       Class::MethodMaker.
1732

NOTES

1734   Object Terminology
1735       In the various OO literature, it seems that a lot of different words
1736       are used to describe only a few different concepts.  If you're not
1737       already an object programmer, then you don't need to worry about all
1738       these fancy words.  But if you are, then you might like to know how to
1739       get at the same concepts in Perl.
1740
1741       For example, it's common to call an object an instance of a class and
1742       to call those objects' methods instance methods.  Data fields peculiar
1743       to each object are often called instance data or object attributes, and
1744       data fields common to all members of that class are class data, class
1745       attributes, or static data members.
1746
1747       Also, base class, generic class, and superclass all describe the same
1748       notion, whereas derived class, specific class, and subclass describe
1749       the other related one.
1750
1751       C++ programmers have static methods and virtual methods, but Perl only
1752       has class methods and object methods.  Actually, Perl only has methods.
1753       Whether a method gets used as a class or object method is by usage
1754       only.  You could accidentally call a class method (one expecting a
1755       string argument) on an object (one expecting a reference), or vice
1756       versa.
1757
1758       From the C++ perspective, all methods in Perl are virtual.  This, by
1759       the way, is why they are never checked for function prototypes in the
1760       argument list as regular builtin and user-defined functions can be.
1761
1762       Because a class is itself something of an object, Perl's classes can be
1763       taken as describing both a "class as meta-object" (also called object
1764       factory) philosophy and the "class as type definition" (declaring
1765       behaviour, not defining mechanism) idea.  C++ supports the latter
1766       notion, but not the former.
1767

SEE ALSO

1769       The following manpages will doubtless provide more background for this
1770       one: perlmod, perlref, perlobj, perlbot, perltie, and overload.
1771
1772       perlboot is a kinder, gentler introduction to object-oriented
1773       programming.
1774
1775       perltooc provides more detail on class data.
1776
1777       Some modules which might prove interesting are Class::Accessor,
1778       Class::Class, Class::Contract, Class::Data::Inheritable,
1779       Class::MethodMaker and Tie::SecureHash
1780
1782       Copyright (c) 1997, 1998 Tom Christiansen All rights reserved.
1783
1784       This documentation is free; you can redistribute it and/or modify it
1785       under the same terms as Perl itself.
1786
1787       Irrespective of its distribution, all code examples in this file are
1788       hereby placed into the public domain.  You are permitted and encouraged
1789       to use this code in your own programs for fun or for profit as you see
1790       fit.  A simple comment in the code giving credit would be courteous but
1791       is not required.
1792
1794   Acknowledgments
1795       Thanks to Larry Wall, Roderick Schertler, Gurusamy Sarathy, Dean
1796       Roehrich, Raphael Manfredi, Brent Halsey, Greg Bacon, Brad Appleton,
1797       and many others for their helpful comments.
1798
1799
1800
1801perl v5.10.1                      2009-02-12                       PERLTOOT(1)
Impressum