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