Re: [PATCH] Fix PERL_MALLOC_WRAP change for Win32
[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
8939ba94 68running Unix or Plan 9, but something like Mac OS or VMS, the directory
5f05dabc 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
c47ff5f1 114And so you could get at C<< $rec->{NAME} >> to find "Jason", or
115C<< @{ $rec->{PEERS} } >> to get at "Norbert", "Rhys", and "Phineas".
5f05dabc 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
8257a158 428Alternatively, you could use the Class::Data::Inheritable module from
429CPAN.
430
431
5f05dabc 432=head2 Accessing Class Data
433
434It turns out that this is not really a good way to go about handling
435class data. A good scalable rule is that I<you must never reference class
436data directly from an object method>. Otherwise you aren't building a
437scalable, inheritable class. The object must be the rendezvous point
438for all operations, especially from an object method. The globals
439(class data) would in some sense be in the "wrong" package in your
440derived classes. In Perl, methods execute in the context of the class
441they were defined in, I<not> that of the object that triggered them.
442Therefore, namespace visibility of package globals in methods is unrelated
443to inheritance.
444
445Got that? Maybe not. Ok, let's say that some other class "borrowed"
446(well, inherited) the DESTROY method as it was defined above. When those
8d9aa5e0 447objects are destroyed, the original $Census variable will be altered,
5f05dabc 448not the one in the new class's package namespace. Perhaps this is what
449you want, but probably it isn't.
450
451Here's how to fix this. We'll store a reference to the data in the
452value accessed by the hash key "_CENSUS". Why the underscore? Well,
453mostly because an initial underscore already conveys strong feelings
454of magicalness to a C programmer. It's really just a mnemonic device
455to remind ourselves that this field is special and not to be used as
456a public data member in the same way that NAME, AGE, and PEERS are.
457(Because we've been developing this code under the strict pragma, prior
a6006777 458to perl version 5.004 we'll have to quote the field name.)
5f05dabc 459
460 sub new {
461 my $proto = shift;
462 my $class = ref($proto) || $proto;
463 my $self = {};
464 $self->{NAME} = undef;
465 $self->{AGE} = undef;
466 $self->{PEERS} = [];
467 # "private" data
468 $self->{"_CENSUS"} = \$Census;
469 bless ($self, $class);
470 ++ ${ $self->{"_CENSUS"} };
471 return $self;
472 }
473
474 sub population {
475 my $self = shift;
476 if (ref $self) {
477 return ${ $self->{"_CENSUS"} };
478 } else {
479 return $Census;
480 }
481 }
482
483 sub DESTROY {
484 my $self = shift;
485 -- ${ $self->{"_CENSUS"} };
486 }
487
488=head2 Debugging Methods
489
490It's common for a class to have a debugging mechanism. For example,
491you might want to see when objects are created or destroyed. To do that,
492add a debugging variable as a file-scoped lexical. For this, we'll pull
493in the standard Carp module to emit our warnings and fatal messages.
494That way messages will come out with the caller's filename and
495line number instead of our own; if we wanted them to be from our own
496perspective, we'd just use die() and warn() directly instead of croak()
497and carp() respectively.
498
499 use Carp;
500 my $Debugging = 0;
501
502Now add a new class method to access the variable.
503
504 sub debug {
505 my $class = shift;
506 if (ref $class) { confess "Class method called as object method" }
507 unless (@_ == 1) { confess "usage: CLASSNAME->debug(level)" }
508 $Debugging = shift;
509 }
510
511Now fix up DESTROY to murmur a bit as the moribund object expires:
512
513 sub DESTROY {
514 my $self = shift;
515 if ($Debugging) { carp "Destroying $self " . $self->name }
516 -- ${ $self->{"_CENSUS"} };
517 }
518
519One could conceivably make a per-object debug state. That
520way you could call both of these:
521
522 Person->debug(1); # entire class
523 $him->debug(1); # just this object
524
525To do so, we need our debugging method to be a "bimodal" one, one that
526works on both classes I<and> objects. Therefore, adjust the debug()
527and DESTROY methods as follows:
528
529 sub debug {
530 my $self = shift;
531 confess "usage: thing->debug(level)" unless @_ == 1;
532 my $level = shift;
533 if (ref($self)) {
534 $self->{"_DEBUG"} = $level; # just myself
535 } else {
536 $Debugging = $level; # whole class
537 }
538 }
539
540 sub DESTROY {
541 my $self = shift;
542 if ($Debugging || $self->{"_DEBUG"}) {
543 carp "Destroying $self " . $self->name;
544 }
545 -- ${ $self->{"_CENSUS"} };
546 }
547
8d9aa5e0 548What happens if a derived class (which we'll call Employee) inherits
c47ff5f1 549methods from this Person base class? Then C<< Employee->debug() >>, when called
8d9aa5e0 550as a class method, manipulates $Person::Debugging not $Employee::Debugging.
5f05dabc 551
552=head2 Class Destructors
553
554The object destructor handles the death of each distinct object. But sometimes
555you want a bit of cleanup when the entire class is shut down, which
556currently only happens when the program exits. To make such a
557I<class destructor>, create a function in that class's package named
558END. This works just like the END function in traditional modules,
559meaning that it gets called whenever your program exits unless it execs
560or dies of an uncaught signal. For example,
561
562 sub END {
563 if ($Debugging) {
564 print "All persons are going away now.\n";
565 }
566 }
567
568When the program exits, all the class destructors (END functions) are
569be called in the opposite order that they were loaded in (LIFO order).
570
571=head2 Documenting the Interface
572
573And there you have it: we've just shown you the I<implementation> of this
574Person class. Its I<interface> would be its documentation. Usually this
575means putting it in pod ("plain old documentation") format right there
576in the same file. In our Person example, we would place the following
577docs anywhere in the Person.pm file. Even though it looks mostly like
578code, it's not. It's embedded documentation such as would be used by
579the pod2man, pod2html, or pod2text programs. The Perl compiler ignores
580pods entirely, just as the translators ignore code. Here's an example of
581some pods describing the informal interface:
582
583 =head1 NAME
584
585 Person - class to implement people
586
587 =head1 SYNOPSIS
588
589 use Person;
590
591 #################
592 # class methods #
593 #################
594 $ob = Person->new;
595 $count = Person->population;
596
597 #######################
598 # object data methods #
599 #######################
600
601 ### get versions ###
602 $who = $ob->name;
603 $years = $ob->age;
604 @pals = $ob->peers;
605
606 ### set versions ###
607 $ob->name("Jason");
608 $ob->age(23);
609 $ob->peers( "Norbert", "Rhys", "Phineas" );
610
611 ########################
612 # other object methods #
613 ########################
614
615 $phrase = $ob->exclaim;
616 $ob->happy_birthday;
617
618 =head1 DESCRIPTION
619
620 The Person class implements dah dee dah dee dah....
621
622That's all there is to the matter of interface versus implementation.
623A programmer who opens up the module and plays around with all the private
624little shiny bits that were safely locked up behind the interface contract
625has voided the warranty, and you shouldn't worry about their fate.
626
627=head1 Aggregation
628
629Suppose you later want to change the class to implement better names.
630Perhaps you'd like to support both given names (called Christian names,
631irrespective of one's religion) and family names (called surnames), plus
632nicknames and titles. If users of your Person class have been properly
633accessing it through its documented interface, then you can easily change
634the underlying implementation. If they haven't, then they lose and
635it's their fault for breaking the contract and voiding their warranty.
636
637To do this, we'll make another class, this one called Fullname. What's
638the Fullname class look like? To answer that question, you have to
639first figure out how you want to use it. How about we use it this way:
640
641 $him = Person->new();
642 $him->fullname->title("St");
643 $him->fullname->christian("Thomas");
644 $him->fullname->surname("Aquinas");
645 $him->fullname->nickname("Tommy");
646 printf "His normal name is %s\n", $him->name;
647 printf "But his real name is %s\n", $him->fullname->as_string;
648
649Ok. To do this, we'll change Person::new() so that it supports
650a full name field this way:
651
652 sub new {
653 my $proto = shift;
654 my $class = ref($proto) || $proto;
655 my $self = {};
656 $self->{FULLNAME} = Fullname->new();
657 $self->{AGE} = undef;
658 $self->{PEERS} = [];
659 $self->{"_CENSUS"} = \$Census;
660 bless ($self, $class);
661 ++ ${ $self->{"_CENSUS"} };
662 return $self;
663 }
664
665 sub fullname {
666 my $self = shift;
667 return $self->{FULLNAME};
668 }
669
670Then to support old code, define Person::name() this way:
671
672 sub name {
673 my $self = shift;
674 return $self->{FULLNAME}->nickname(@_)
675 || $self->{FULLNAME}->christian(@_);
676 }
677
678Here's the Fullname class. We'll use the same technique
679of using a hash reference to hold data fields, and methods
680by the appropriate name to access them:
681
682 package Fullname;
683 use strict;
684
685 sub new {
686 my $proto = shift;
687 my $class = ref($proto) || $proto;
688 my $self = {
689 TITLE => undef,
690 CHRISTIAN => undef,
691 SURNAME => undef,
692 NICK => undef,
693 };
694 bless ($self, $class);
695 return $self;
696 }
697
698 sub christian {
699 my $self = shift;
700 if (@_) { $self->{CHRISTIAN} = shift }
701 return $self->{CHRISTIAN};
702 }
703
704 sub surname {
705 my $self = shift;
706 if (@_) { $self->{SURNAME} = shift }
707 return $self->{SURNAME};
708 }
709
710 sub nickname {
711 my $self = shift;
712 if (@_) { $self->{NICK} = shift }
713 return $self->{NICK};
714 }
715
716 sub title {
717 my $self = shift;
718 if (@_) { $self->{TITLE} = shift }
719 return $self->{TITLE};
720 }
721
722 sub as_string {
723 my $self = shift;
724 my $name = join(" ", @$self{'CHRISTIAN', 'SURNAME'});
725 if ($self->{TITLE}) {
726 $name = $self->{TITLE} . " " . $name;
727 }
728 return $name;
729 }
730
731 1;
732
733Finally, here's the test program:
734
735 #!/usr/bin/perl -w
736 use strict;
737 use Person;
738 sub END { show_census() }
739
740 sub show_census () {
741 printf "Current population: %d\n", Person->population;
742 }
743
744 Person->debug(1);
745
746 show_census();
747
748 my $him = Person->new();
749
750 $him->fullname->christian("Thomas");
751 $him->fullname->surname("Aquinas");
752 $him->fullname->nickname("Tommy");
753 $him->fullname->title("St");
754 $him->age(1);
755
69fc43e8 756 printf "%s is really %s.\n", $him->name, $him->fullname->as_string;
5f05dabc 757 printf "%s's age: %d.\n", $him->name, $him->age;
758 $him->happy_birthday;
759 printf "%s's age: %d.\n", $him->name, $him->age;
760
761 show_census();
762
763=head1 Inheritance
764
765Object-oriented programming systems all support some notion of
766inheritance. Inheritance means allowing one class to piggy-back on
767top of another one so you don't have to write the same code again and
768again. It's about software reuse, and therefore related to Laziness,
769the principal virtue of a programmer. (The import/export mechanisms in
770traditional modules are also a form of code reuse, but a simpler one than
771the true inheritance that you find in object modules.)
772
773Sometimes the syntax of inheritance is built into the core of the
774language, and sometimes it's not. Perl has no special syntax for
775specifying the class (or classes) to inherit from. Instead, it's all
776strictly in the semantics. Each package can have a variable called @ISA,
777which governs (method) inheritance. If you try to call a method on an
778object or class, and that method is not found in that object's package,
779Perl then looks to @ISA for other packages to go looking through in
780search of the missing method.
781
782Like the special per-package variables recognized by Exporter (such as
783@EXPORT, @EXPORT_OK, @EXPORT_FAIL, %EXPORT_TAGS, and $VERSION), the @ISA
784array I<must> be a package-scoped global and not a file-scoped lexical
785created via my(). Most classes have just one item in their @ISA array.
786In this case, we have what's called "single inheritance", or SI for short.
787
788Consider this class:
789
790 package Employee;
791 use Person;
792 @ISA = ("Person");
793 1;
794
795Not a lot to it, eh? All it's doing so far is loading in another
796class and stating that this one will inherit methods from that
797other class if need be. We have given it none of its own methods.
798We rely upon an Employee to behave just like a Person.
799
800Setting up an empty class like this is called the "empty subclass test";
801that is, making a derived class that does nothing but inherit from a
802base class. If the original base class has been designed properly,
803then the new derived class can be used as a drop-in replacement for the
804old one. This means you should be able to write a program like this:
805
3e3baf6d 806 use Employee;
5f05dabc 807 my $empl = Employee->new();
808 $empl->name("Jason");
809 $empl->age(23);
810 printf "%s is age %d.\n", $empl->name, $empl->age;
811
812By proper design, we mean always using the two-argument form of bless(),
813avoiding direct access of global data, and not exporting anything. If you
814look back at the Person::new() function we defined above, we were careful
815to do that. There's a bit of package data used in the constructor,
816but the reference to this is stored on the object itself and all other
817methods access package data via that reference, so we should be ok.
818
819What do we mean by the Person::new() function -- isn't that actually
820a method? Well, in principle, yes. A method is just a function that
821expects as its first argument a class name (package) or object
822(blessed reference). Person::new() is the function that both the
c47ff5f1 823C<< Person->new() >> method and the C<< Employee->new() >> method end
5f05dabc 824up calling. Understand that while a method call looks a lot like a
825function call, they aren't really quite the same, and if you treat them
826as the same, you'll very soon be left with nothing but broken programs.
827First, the actual underlying calling conventions are different: method
828calls get an extra argument. Second, function calls don't do inheritance,
829but methods do.
830
831 Method Call Resulting Function Call
832 ----------- ------------------------
833 Person->new() Person::new("Person")
834 Employee->new() Person::new("Employee")
835
836So don't use function calls when you mean to call a method.
837
838If an employee is just a Person, that's not all too very interesting.
839So let's add some other methods. We'll give our employee
840data fields to access their salary, their employee ID, and their
841start date.
842
843If you're getting a little tired of creating all these nearly identical
844methods just to get at the object's data, do not despair. Later,
845we'll describe several different convenience mechanisms for shortening
846this up. Meanwhile, here's the straight-forward way:
847
848 sub salary {
849 my $self = shift;
850 if (@_) { $self->{SALARY} = shift }
851 return $self->{SALARY};
852 }
853
854 sub id_number {
855 my $self = shift;
856 if (@_) { $self->{ID} = shift }
857 return $self->{ID};
858 }
859
860 sub start_date {
861 my $self = shift;
862 if (@_) { $self->{START_DATE} = shift }
863 return $self->{START_DATE};
864 }
865
866=head2 Overridden Methods
867
868What happens when both a derived class and its base class have the same
869method defined? Well, then you get the derived class's version of that
870method. For example, let's say that we want the peers() method called on
871an employee to act a bit differently. Instead of just returning the list
872of peer names, let's return slightly different strings. So doing this:
873
874 $empl->peers("Peter", "Paul", "Mary");
875 printf "His peers are: %s\n", join(", ", $empl->peers);
876
877will produce:
878
879 His peers are: PEON=PETER, PEON=PAUL, PEON=MARY
880
881To do this, merely add this definition into the Employee.pm file:
882
883 sub peers {
884 my $self = shift;
885 if (@_) { @{ $self->{PEERS} } = @_ }
886 return map { "PEON=\U$_" } @{ $self->{PEERS} };
887 }
888
889There, we've just demonstrated the high-falutin' concept known in certain
890circles as I<polymorphism>. We've taken on the form and behaviour of
891an existing object, and then we've altered it to suit our own purposes.
892This is a form of Laziness. (Getting polymorphed is also what happens
893when the wizard decides you'd look better as a frog.)
894
895Every now and then you'll want to have a method call trigger both its
68dc0745 896derived class (also known as "subclass") version as well as its base class
5f05dabc 897(also known as "superclass") version. In practice, constructors and
898destructors are likely to want to do this, and it probably also makes
899sense in the debug() method we showed previously.
900
901To do this, add this to Employee.pm:
902
903 use Carp;
904 my $Debugging = 0;
905
906 sub debug {
907 my $self = shift;
908 confess "usage: thing->debug(level)" unless @_ == 1;
909 my $level = shift;
910 if (ref($self)) {
911 $self->{"_DEBUG"} = $level;
912 } else {
913 $Debugging = $level; # whole class
914 }
915 Person::debug($self, $Debugging); # don't really do this
916 }
917
918As you see, we turn around and call the Person package's debug() function.
919But this is far too fragile for good design. What if Person doesn't
920have a debug() function, but is inheriting I<its> debug() method
921from elsewhere? It would have been slightly better to say
922
923 Person->debug($Debugging);
924
925But even that's got too much hard-coded. It's somewhat better to say
926
927 $self->Person::debug($Debugging);
928
929Which is a funny way to say to start looking for a debug() method up
930in Person. This strategy is more often seen on overridden object methods
931than on overridden class methods.
932
933There is still something a bit off here. We've hard-coded our
934superclass's name. This in particular is bad if you change which classes
935you inherit from, or add others. Fortunately, the pseudoclass SUPER
936comes to the rescue here.
937
71be2cbc 938 $self->SUPER::debug($Debugging);
5f05dabc 939
940This way it starts looking in my class's @ISA. This only makes sense
941from I<within> a method call, though. Don't try to access anything
942in SUPER:: from anywhere else, because it doesn't exist outside
029f3b44 943an overridden method call. Note that C<SUPER> refers to the superclass of
944the current package, I<not> to the superclass of C<$self>.
5f05dabc 945
946Things are getting a bit complicated here. Have we done anything
947we shouldn't? As before, one way to test whether we're designing
948a decent class is via the empty subclass test. Since we already have
949an Employee class that we're trying to check, we'd better get a new
950empty subclass that can derive from Employee. Here's one:
951
952 package Boss;
953 use Employee; # :-)
954 @ISA = qw(Employee);
955
956And here's the test program:
957
958 #!/usr/bin/perl -w
959 use strict;
960 use Boss;
961 Boss->debug(1);
962
963 my $boss = Boss->new();
964
965 $boss->fullname->title("Don");
966 $boss->fullname->surname("Pichon Alvarez");
967 $boss->fullname->christian("Federico Jesus");
968 $boss->fullname->nickname("Fred");
969
970 $boss->age(47);
971 $boss->peers("Frank", "Felipe", "Faust");
972
69fc43e8 973 printf "%s is age %d.\n", $boss->fullname->as_string, $boss->age;
5f05dabc 974 printf "His peers are: %s\n", join(", ", $boss->peers);
975
976Running it, we see that we're still ok. If you'd like to dump out your
977object in a nice format, somewhat like the way the 'x' command works in
978the debugger, you could use the Data::Dumper module from CPAN this way:
979
980 use Data::Dumper;
981 print "Here's the boss:\n";
982 print Dumper($boss);
983
984Which shows us something like this:
985
986 Here's the boss:
987 $VAR1 = bless( {
988 _CENSUS => \1,
989 FULLNAME => bless( {
990 TITLE => 'Don',
991 SURNAME => 'Pichon Alvarez',
992 NICK => 'Fred',
993 CHRISTIAN => 'Federico Jesus'
994 }, 'Fullname' ),
995 AGE => 47,
996 PEERS => [
997 'Frank',
998 'Felipe',
999 'Faust'
1000 ]
1001 }, 'Boss' );
1002
1003Hm.... something's missing there. What about the salary, start date,
1004and ID fields? Well, we never set them to anything, even undef, so they
1005don't show up in the hash's keys. The Employee class has no new() method
1006of its own, and the new() method in Person doesn't know about Employees.
1007(Nor should it: proper OO design dictates that a subclass be allowed to
1008know about its immediate superclass, but never vice-versa.) So let's
1009fix up Employee::new() this way:
1010
1011 sub new {
1012 my $proto = shift;
1013 my $class = ref($proto) || $proto;
1014 my $self = $class->SUPER::new();
1015 $self->{SALARY} = undef;
1016 $self->{ID} = undef;
1017 $self->{START_DATE} = undef;
1018 bless ($self, $class); # reconsecrate
1019 return $self;
1020 }
1021
1022Now if you dump out an Employee or Boss object, you'll find
1023that new fields show up there now.
1024
1025=head2 Multiple Inheritance
1026
1027Ok, at the risk of confusing beginners and annoying OO gurus, it's
1028time to confess that Perl's object system includes that controversial
1029notion known as multiple inheritance, or MI for short. All this means
1030is that rather than having just one parent class who in turn might
1031itself have a parent class, etc., that you can directly inherit from
1032two or more parents. It's true that some uses of MI can get you into
1033trouble, although hopefully not quite so much trouble with Perl as with
1034dubiously-OO languages like C++.
1035
1036The way it works is actually pretty simple: just put more than one package
1037name in your @ISA array. When it comes time for Perl to go finding
1038methods for your object, it looks at each of these packages in order.
1039Well, kinda. It's actually a fully recursive, depth-first order.
1040Consider a bunch of @ISA arrays like this:
1041
1042 @First::ISA = qw( Alpha );
1043 @Second::ISA = qw( Beta );
1044 @Third::ISA = qw( First Second );
1045
1046If you have an object of class Third:
1047
1048 my $ob = Third->new();
1049 $ob->spin();
1050
1051How do we find a spin() method (or a new() method for that matter)?
1052Because the search is depth-first, classes will be looked up
1053in the following order: Third, First, Alpha, Second, and Beta.
1054
1055In practice, few class modules have been seen that actually
1056make use of MI. One nearly always chooses simple containership of
1057one class within another over MI. That's why our Person
1058object I<contained> a Fullname object. That doesn't mean
1059it I<was> one.
1060
1061However, there is one particular area where MI in Perl is rampant:
1062borrowing another class's class methods. This is rather common,
1063especially with some bundled "objectless" classes,
1064like Exporter, DynaLoader, AutoLoader, and SelfLoader. These classes
1065do not provide constructors; they exist only so you may inherit their
1066class methods. (It's not entirely clear why inheritance was done
1067here rather than traditional module importation.)
1068
1069For example, here is the POSIX module's @ISA:
1070
1071 package POSIX;
1072 @ISA = qw(Exporter DynaLoader);
1073
1074The POSIX module isn't really an object module, but then,
1075neither are Exporter or DynaLoader. They're just lending their
1076classes' behaviours to POSIX.
1077
1078Why don't people use MI for object methods much? One reason is that
1079it can have complicated side-effects. For one thing, your inheritance
1080graph (no longer a tree) might converge back to the same base class.
1081Although Perl guards against recursive inheritance, merely having parents
1082who are related to each other via a common ancestor, incestuous though
1083it sounds, is not forbidden. What if in our Third class shown above we
1084wanted its new() method to also call both overridden constructors in its
1085two parent classes? The SUPER notation would only find the first one.
1086Also, what about if the Alpha and Beta classes both had a common ancestor,
1087like Nought? If you kept climbing up the inheritance tree calling
1088overridden methods, you'd end up calling Nought::new() twice,
1089which might well be a bad idea.
1090
1091=head2 UNIVERSAL: The Root of All Objects
1092
1093Wouldn't it be convenient if all objects were rooted at some ultimate
1094base class? That way you could give every object common methods without
1095having to go and add it to each and every @ISA. Well, it turns out that
1096you can. You don't see it, but Perl tacitly and irrevocably assumes
1097that there's an extra element at the end of @ISA: the class UNIVERSAL.
a6006777 1098In version 5.003, there were no predefined methods there, but you could put
5f05dabc 1099whatever you felt like into it.
1100
a6006777 1101However, as of version 5.004 (or some subversive releases, like 5.003_08),
54310121 1102UNIVERSAL has some methods in it already. These are builtin to your Perl
5f05dabc 1103binary, so they don't take any extra time to load. Predefined methods
1104include isa(), can(), and VERSION(). isa() tells you whether an object or
1105class "is" another one without having to traverse the hierarchy yourself:
1106
1107 $has_io = $fd->isa("IO::Handle");
1108 $itza_handle = IO::Socket->isa("IO::Handle");
1109
1110The can() method, called against that object or class, reports back
1111whether its string argument is a callable method name in that class.
1112In fact, it gives you back a function reference to that method:
1113
1114 $his_print_method = $obj->can('as_string');
1115
1116Finally, the VERSION method checks whether the class (or the object's
1117class) has a package global called $VERSION that's high enough, as in:
1118
1119 Some_Module->VERSION(3.0);
1120 $his_vers = $ob->VERSION();
1121
1122However, we don't usually call VERSION ourselves. (Remember that an all
68dc0745 1123uppercase function name is a Perl convention that indicates that the
5f05dabc 1124function will be automatically used by Perl in some way.) In this case,
1125it happens when you say
1126
1127 use Some_Module 3.0;
1128
8d9aa5e0 1129If you wanted to add version checking to your Person class explained
5f05dabc 1130above, just add this to Person.pm:
1131
77ca0c92 1132 our $VERSION = '1.1';
5f05dabc 1133
0184c62d 1134and then in Employee.pm you can say
5f05dabc 1135
0184c62d 1136 use Person 1.1;
5f05dabc 1137
1138And it would make sure that you have at least that version number or
1139higher available. This is not the same as loading in that exact version
1140number. No mechanism currently exists for concurrent installation of
1141multiple versions of a module. Lamentably.
1142
1143=head1 Alternate Object Representations
1144
1145Nothing requires objects to be implemented as hash references. An object
1146can be any sort of reference so long as its referent has been suitably
1147blessed. That means scalar, array, and code references are also fair
1148game.
1149
1150A scalar would work if the object has only one datum to hold. An array
1151would work for most cases, but makes inheritance a bit dodgy because
1152you have to invent new indices for the derived classes.
1153
1154=head2 Arrays as Objects
1155
1156If the user of your class honors the contract and sticks to the advertised
1157interface, then you can change its underlying interface if you feel
1158like it. Here's another implementation that conforms to the same
1159interface specification. This time we'll use an array reference
1160instead of a hash reference to represent the object.
1161
1162 package Person;
1163 use strict;
1164
1165 my($NAME, $AGE, $PEERS) = ( 0 .. 2 );
1166
1167 ############################################
1168 ## the object constructor (array version) ##
1169 ############################################
1170 sub new {
1171 my $self = [];
1172 $self->[$NAME] = undef; # this is unnecessary
68dc0745 1173 $self->[$AGE] = undef; # as is this
5f05dabc 1174 $self->[$PEERS] = []; # but this isn't, really
1175 bless($self);
1176 return $self;
1177 }
1178
1179 sub name {
1180 my $self = shift;
1181 if (@_) { $self->[$NAME] = shift }
1182 return $self->[$NAME];
1183 }
1184
1185 sub age {
1186 my $self = shift;
1187 if (@_) { $self->[$AGE] = shift }
1188 return $self->[$AGE];
1189 }
1190
1191 sub peers {
1192 my $self = shift;
1193 if (@_) { @{ $self->[$PEERS] } = @_ }
1194 return @{ $self->[$PEERS] };
1195 }
1196
1197 1; # so the require or use succeeds
1198
8d9aa5e0 1199You might guess that the array access would be a lot faster than the
1200hash access, but they're actually comparable. The array is a I<little>
5f05dabc 1201bit faster, but not more than ten or fifteen percent, even when you
1202replace the variables above like $AGE with literal numbers, like 1.
1203A bigger difference between the two approaches can be found in memory use.
1204A hash representation takes up more memory than an array representation
8d9aa5e0 1205because you have to allocate memory for the keys as well as for the values.
a6006777 1206However, it really isn't that bad, especially since as of version 5.004,
5f05dabc 1207memory is only allocated once for a given hash key, no matter how many
1208hashes have that key. It's expected that sometime in the future, even
1209these differences will fade into obscurity as more efficient underlying
1210representations are devised.
1211
1212Still, the tiny edge in speed (and somewhat larger one in memory)
1213is enough to make some programmers choose an array representation
1214for simple classes. There's still a little problem with
1215scalability, though, because later in life when you feel
1216like creating subclasses, you'll find that hashes just work
1217out better.
1218
1219=head2 Closures as Objects
1220
1221Using a code reference to represent an object offers some fascinating
1222possibilities. We can create a new anonymous function (closure) who
1223alone in all the world can see the object's data. This is because we
1224put the data into an anonymous hash that's lexically visible only to
1225the closure we create, bless, and return as the object. This object's
1226methods turn around and call the closure as a regular subroutine call,
1227passing it the field we want to affect. (Yes,
1228the double-function call is slow, but if you wanted fast, you wouldn't
1229be using objects at all, eh? :-)
1230
1231Use would be similar to before:
1232
1233 use Person;
1234 $him = Person->new();
1235 $him->name("Jason");
1236 $him->age(23);
1237 $him->peers( [ "Norbert", "Rhys", "Phineas" ] );
1238 printf "%s is %d years old.\n", $him->name, $him->age;
1239 print "His peers are: ", join(", ", @{$him->peers}), "\n";
1240
1241but the implementation would be radically, perhaps even sublimely
1242different:
1243
1244 package Person;
1245
1246 sub new {
1247 my $that = shift;
1248 my $class = ref($that) || $that;
1249 my $self = {
1250 NAME => undef,
1251 AGE => undef,
1252 PEERS => [],
1253 };
1254 my $closure = sub {
1255 my $field = shift;
1256 if (@_) { $self->{$field} = shift }
1257 return $self->{$field};
1258 };
1259 bless($closure, $class);
1260 return $closure;
1261 }
1262
1263 sub name { &{ $_[0] }("NAME", @_[ 1 .. $#_ ] ) }
1264 sub age { &{ $_[0] }("AGE", @_[ 1 .. $#_ ] ) }
1265 sub peers { &{ $_[0] }("PEERS", @_[ 1 .. $#_ ] ) }
1266
1267 1;
1268
1269Because this object is hidden behind a code reference, it's probably a bit
1270mysterious to those whose background is more firmly rooted in standard
1271procedural or object-based programming languages than in functional
1272programming languages whence closures derive. The object
1273created and returned by the new() method is itself not a data reference
1274as we've seen before. It's an anonymous code reference that has within
1275it access to a specific version (lexical binding and instantiation)
1276of the object's data, which are stored in the private variable $self.
1277Although this is the same function each time, it contains a different
1278version of $self.
1279
1280When a method like C<$him-E<gt>name("Jason")> is called, its implicit
8d9aa5e0 1281zeroth argument is the invoking object--just as it is with all method
5f05dabc 1282calls. But in this case, it's our code reference (something like a
1283function pointer in C++, but with deep binding of lexical variables).
1284There's not a lot to be done with a code reference beyond calling it, so
1285that's just what we do when we say C<&{$_[0]}>. This is just a regular
1286function call, not a method call. The initial argument is the string
1287"NAME", and any remaining arguments are whatever had been passed to the
1288method itself.
1289
1290Once we're executing inside the closure that had been created in new(),
1291the $self hash reference suddenly becomes visible. The closure grabs
1292its first argument ("NAME" in this case because that's what the name()
1293method passed it), and uses that string to subscript into the private
1294hash hidden in its unique version of $self.
1295
1296Nothing under the sun will allow anyone outside the executing method to
1297be able to get at this hidden data. Well, nearly nothing. You I<could>
1298single step through the program using the debugger and find out the
1299pieces while you're in the method, but everyone else is out of luck.
1300
1301There, if that doesn't excite the Scheme folks, then I just don't know
1302what will. Translation of this technique into C++, Java, or any other
1303braindead-static language is left as a futile exercise for aficionados
1304of those camps.
1305
1306You could even add a bit of nosiness via the caller() function and
1307make the closure refuse to operate unless called via its own package.
1308This would no doubt satisfy certain fastidious concerns of programming
1309police and related puritans.
1310
1311If you were wondering when Hubris, the third principle virtue of a
1312programmer, would come into play, here you have it. (More seriously,
1313Hubris is just the pride in craftsmanship that comes from having written
1314a sound bit of well-designed code.)
1315
1316=head1 AUTOLOAD: Proxy Methods
1317
1318Autoloading is a way to intercept calls to undefined methods. An autoload
1319routine may choose to create a new function on the fly, either loaded
1320from disk or perhaps just eval()ed right there. This define-on-the-fly
1321strategy is why it's called autoloading.
1322
1323But that's only one possible approach. Another one is to just
1324have the autoloaded method itself directly provide the
1325requested service. When used in this way, you may think
1326of autoloaded methods as "proxy" methods.
1327
1328When Perl tries to call an undefined function in a particular package
1329and that function is not defined, it looks for a function in
1330that same package called AUTOLOAD. If one exists, it's called
1331with the same arguments as the original function would have had.
1332The fully-qualified name of the function is stored in that package's
1333global variable $AUTOLOAD. Once called, the function can do anything
1334it would like, including defining a new function by the right name, and
1335then doing a really fancy kind of C<goto> right to it, erasing itself
1336from the call stack.
1337
1338What does this have to do with objects? After all, we keep talking about
1339functions, not methods. Well, since a method is just a function with
1340an extra argument and some fancier semantics about where it's found,
1341we can use autoloading for methods, too. Perl doesn't start looking
1342for an AUTOLOAD method until it has exhausted the recursive hunt up
1343through @ISA, though. Some programmers have even been known to define
1344a UNIVERSAL::AUTOLOAD method to trap unresolved method calls to any
1345kind of object.
1346
1347=head2 Autoloaded Data Methods
1348
1349You probably began to get a little suspicious about the duplicated
1350code way back earlier when we first showed you the Person class, and
1351then later the Employee class. Each method used to access the
1352hash fields looked virtually identical. This should have tickled
1353that great programming virtue, Impatience, but for the time,
1354we let Laziness win out, and so did nothing. Proxy methods can cure
1355this.
1356
1357Instead of writing a new function every time we want a new data field,
1358we'll use the autoload mechanism to generate (actually, mimic) methods on
1359the fly. To verify that we're accessing a valid member, we will check
1360against an C<_permitted> (pronounced "under-permitted") field, which
1361is a reference to a file-scoped lexical (like a C file static) hash of permitted fields in this record
1362called %fields. Why the underscore? For the same reason as the _CENSUS
1363field we once used: as a marker that means "for internal use only".
1364
1365Here's what the module initialization code and class
1366constructor will look like when taking this approach:
1367
1368 package Person;
1369 use Carp;
77ca0c92 1370 our $AUTOLOAD; # it's a package global
5f05dabc 1371
1372 my %fields = (
1373 name => undef,
1374 age => undef,
1375 peers => undef,
1376 );
1377
1378 sub new {
1379 my $that = shift;
1380 my $class = ref($that) || $that;
1381 my $self = {
1382 _permitted => \%fields,
1383 %fields,
1384 };
1385 bless $self, $class;
1386 return $self;
1387 }
1388
1389If we wanted our record to have default values, we could fill those in
1390where current we have C<undef> in the %fields hash.
1391
1392Notice how we saved a reference to our class data on the object itself?
1393Remember that it's important to access class data through the object
1394itself instead of having any method reference %fields directly, or else
1395you won't have a decent inheritance.
1396
1397The real magic, though, is going to reside in our proxy method, which
1398will handle all calls to undefined methods for objects of class Person
1399(or subclasses of Person). It has to be called AUTOLOAD. Again, it's
1400all caps because it's called for us implicitly by Perl itself, not by
1401a user directly.
1402
1403 sub AUTOLOAD {
1404 my $self = shift;
1405 my $type = ref($self)
1406 or croak "$self is not an object";
1407
1408 my $name = $AUTOLOAD;
1409 $name =~ s/.*://; # strip fully-qualified portion
1410
1411 unless (exists $self->{_permitted}->{$name} ) {
1412 croak "Can't access `$name' field in class $type";
1413 }
1414
1415 if (@_) {
1416 return $self->{$name} = shift;
1417 } else {
1418 return $self->{$name};
1419 }
1420 }
1421
1422Pretty nifty, eh? All we have to do to add new data fields
1423is modify %fields. No new functions need be written.
1424
1425I could have avoided the C<_permitted> field entirely, but I
1426wanted to demonstrate how to store a reference to class data on the
54310121 1427object so you wouldn't have to access that class data
5f05dabc 1428directly from an object method.
1429
1430=head2 Inherited Autoloaded Data Methods
1431
1432But what about inheritance? Can we define our Employee
1433class similarly? Yes, so long as we're careful enough.
1434
1435Here's how to be careful:
1436
1437 package Employee;
1438 use Person;
1439 use strict;
77ca0c92 1440 our @ISA = qw(Person);
5f05dabc 1441
1442 my %fields = (
1443 id => undef,
1444 salary => undef,
1445 );
1446
1447 sub new {
1448 my $that = shift;
1449 my $class = ref($that) || $that;
1450 my $self = bless $that->SUPER::new(), $class;
1451 my($element);
1452 foreach $element (keys %fields) {
1453 $self->{_permitted}->{$element} = $fields{$element};
1454 }
1455 @{$self}{keys %fields} = values %fields;
1456 return $self;
1457 }
1458
1459Once we've done this, we don't even need to have an
1460AUTOLOAD function in the Employee package, because
1461we'll grab Person's version of that via inheritance,
1462and it will all work out just fine.
1463
1464=head1 Metaclassical Tools
1465
1466Even though proxy methods can provide a more convenient approach to making
1467more struct-like classes than tediously coding up data methods as
1468functions, it still leaves a bit to be desired. For one thing, it means
1469you have to handle bogus calls that you don't mean to trap via your proxy.
1470It also means you have to be quite careful when dealing with inheritance,
1471as detailed above.
1472
1473Perl programmers have responded to this by creating several different
1474class construction classes. These metaclasses are classes
1475that create other classes. A couple worth looking at are
8cc95fdb 1476Class::Struct and Alias. These and other related metaclasses can be
5f05dabc 1477found in the modules directory on CPAN.
1478
8cc95fdb 1479=head2 Class::Struct
5f05dabc 1480
8cc95fdb 1481One of the older ones is Class::Struct. In fact, its syntax and
5f05dabc 1482interface were sketched out long before perl5 even solidified into a
8d9aa5e0 1483real thing. What it does is provide you a way to "declare" a class
1484as having objects whose fields are of a specific type. The function
1485that does this is called, not surprisingly enough, struct(). Because
1486structures or records are not base types in Perl, each time you want to
1487create a class to provide a record-like data object, you yourself have
1488to define a new() method, plus separate data-access methods for each of
1489that record's fields. You'll quickly become bored with this process.
8cc95fdb 1490The Class::Struct::struct() function alleviates this tedium.
5f05dabc 1491
1492Here's a simple example of using it:
1493
8cc95fdb 1494 use Class::Struct qw(struct);
5f05dabc 1495 use Jobbie; # user-defined; see below
1496
1497 struct 'Fred' => {
1498 one => '$',
1499 many => '@',
0184c62d 1500 profession => 'Jobbie', # does not call Jobbie->new()
5f05dabc 1501 };
1502
0184c62d 1503 $ob = Fred->new(profession => Jobbie->new());
5f05dabc 1504 $ob->one("hmmmm");
1505
1506 $ob->many(0, "here");
1507 $ob->many(1, "you");
1508 $ob->many(2, "go");
1509 print "Just set: ", $ob->many(2), "\n";
1510
1511 $ob->profession->salary(10_000);
1512
1513You can declare types in the struct to be basic Perl types, or
1514user-defined types (classes). User types will be initialized by calling
1515that class's new() method.
1516
0184c62d 1517Take care that the C<Jobbie> object is not created automatically by the
1518C<Fred> class's new() method, so you should specify a C<Jobbie> object
1519when you create an instance of C<Fred>.
1520
5f05dabc 1521Here's a real-world example of using struct generation. Let's say you
1522wanted to override Perl's idea of gethostbyname() and gethostbyaddr() so
1523that they would return objects that acted like C structures. We don't
1524care about high-falutin' OO gunk. All we want is for these objects to
1525act like structs in the C sense.
1526
1527 use Socket;
1528 use Net::hostent;
1529 $h = gethostbyname("perl.com"); # object return
1530 printf "perl.com's real name is %s, address %s\n",
1531 $h->name, inet_ntoa($h->addr);
1532
8cc95fdb 1533Here's how to do this using the Class::Struct module.
5f05dabc 1534The crux is going to be this call:
1535
1536 struct 'Net::hostent' => [ # note bracket
1537 name => '$',
1538 aliases => '@',
1539 addrtype => '$',
1540 'length' => '$',
1541 addr_list => '@',
1542 ];
1543
1544Which creates object methods of those names and types.
1545It even creates a new() method for us.
1546
1547We could also have implemented our object this way:
1548
1549 struct 'Net::hostent' => { # note brace
1550 name => '$',
1551 aliases => '@',
1552 addrtype => '$',
1553 'length' => '$',
1554 addr_list => '@',
1555 };
1556
8cc95fdb 1557and then Class::Struct would have used an anonymous hash as the object
5f05dabc 1558type, instead of an anonymous array. The array is faster and smaller,
1559but the hash works out better if you eventually want to do inheritance.
1560Since for this struct-like object we aren't planning on inheritance,
1561this time we'll opt for better speed and size over better flexibility.
1562
1563Here's the whole implementation:
1564
1565 package Net::hostent;
1566 use strict;
1567
1568 BEGIN {
1569 use Exporter ();
77ca0c92 1570 our @EXPORT = qw(gethostbyname gethostbyaddr gethost);
1571 our @EXPORT_OK = qw(
1572 $h_name @h_aliases
1573 $h_addrtype $h_length
1574 @h_addr_list $h_addr
1575 );
1576 our %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
5f05dabc 1577 }
77ca0c92 1578 our @EXPORT_OK;
5f05dabc 1579
8cc95fdb 1580 # Class::Struct forbids use of @ISA
1581 sub import { goto &Exporter::import }
1582
1583 use Class::Struct qw(struct);
5f05dabc 1584 struct 'Net::hostent' => [
1585 name => '$',
1586 aliases => '@',
1587 addrtype => '$',
1588 'length' => '$',
1589 addr_list => '@',
1590 ];
1591
1592 sub addr { shift->addr_list->[0] }
1593
1594 sub populate (@) {
1595 return unless @_;
8cc95fdb 1596 my $hob = new(); # Class::Struct made this!
5f05dabc 1597 $h_name = $hob->[0] = $_[0];
1598 @h_aliases = @{ $hob->[1] } = split ' ', $_[1];
1599 $h_addrtype = $hob->[2] = $_[2];
1600 $h_length = $hob->[3] = $_[3];
1601 $h_addr = $_[4];
1602 @h_addr_list = @{ $hob->[4] } = @_[ (4 .. $#_) ];
1603 return $hob;
1604 }
1605
1606 sub gethostbyname ($) { populate(CORE::gethostbyname(shift)) }
1607
1608 sub gethostbyaddr ($;$) {
1609 my ($addr, $addrtype);
1610 $addr = shift;
1611 require Socket unless @_;
1612 $addrtype = @_ ? shift : Socket::AF_INET();
1613 populate(CORE::gethostbyaddr($addr, $addrtype))
1614 }
1615
1616 sub gethost($) {
1617 if ($_[0] =~ /^\d+(?:\.\d+(?:\.\d+(?:\.\d+)?)?)?$/) {
1618 require Socket;
1619 &gethostbyaddr(Socket::inet_aton(shift));
1620 } else {
1621 &gethostbyname;
1622 }
1623 }
1624
1625 1;
1626
1627We've snuck in quite a fair bit of other concepts besides just dynamic
1628class creation, like overriding core functions, import/export bits,
8cc95fdb 1629function prototyping, short-cut function call via C<&whatever>, and
1630function replacement with C<goto &whatever>. These all mostly make
1631sense from the perspective of a traditional module, but as you can see,
1632we can also use them in an object module.
5f05dabc 1633
1634You can look at other object-based, struct-like overrides of core
1635functions in the 5.004 release of Perl in File::stat, Net::hostent,
1636Net::netent, Net::protoent, Net::servent, Time::gmtime, Time::localtime,
1637User::grent, and User::pwent. These modules have a final component
68dc0745 1638that's all lowercase, by convention reserved for compiler pragmas,
54310121 1639because they affect the compilation and change a builtin function.
5f05dabc 1640They also have the type names that a C programmer would most expect.
1641
1642=head2 Data Members as Variables
1643
1644If you're used to C++ objects, then you're accustomed to being able to
1645get at an object's data members as simple variables from within a method.
1646The Alias module provides for this, as well as a good bit more, such
1647as the possibility of private methods that the object can call but folks
1648outside the class cannot.
1649
1650Here's an example of creating a Person using the Alias module.
1651When you update these magical instance variables, you automatically
1652update value fields in the hash. Convenient, eh?
1653
1654 package Person;
1655
1656 # this is the same as before...
1657 sub new {
1658 my $that = shift;
1659 my $class = ref($that) || $that;
1660 my $self = {
1661 NAME => undef,
1662 AGE => undef,
1663 PEERS => [],
1664 };
1665 bless($self, $class);
1666 return $self;
1667 }
1668
1669 use Alias qw(attr);
77ca0c92 1670 our ($NAME, $AGE, $PEERS);
5f05dabc 1671
1672 sub name {
1673 my $self = attr shift;
1674 if (@_) { $NAME = shift; }
1675 return $NAME;
1676 }
1677
1678 sub age {
1679 my $self = attr shift;
1680 if (@_) { $AGE = shift; }
1681 return $AGE;
1682 }
1683
1684 sub peers {
1685 my $self = attr shift;
1686 if (@_) { @PEERS = @_; }
1687 return @PEERS;
1688 }
1689
1690 sub exclaim {
1691 my $self = attr shift;
1692 return sprintf "Hi, I'm %s, age %d, working with %s",
1693 $NAME, $AGE, join(", ", @PEERS);
1694 }
1695
1696 sub happy_birthday {
1697 my $self = attr shift;
1698 return ++$AGE;
1699 }
1700
77ca0c92 1701The need for the C<our> declaration is because what Alias does
5f05dabc 1702is play with package globals with the same name as the fields. To use
54310121 1703globals while C<use strict> is in effect, you have to predeclare them.
5f05dabc 1704These package variables are localized to the block enclosing the attr()
1705call just as if you'd used a local() on them. However, that means that
1706they're still considered global variables with temporary values, just
1707as with any other local().
1708
1709It would be nice to combine Alias with
8cc95fdb 1710something like Class::Struct or Class::MethodMaker.
5f05dabc 1711
13a2d996 1712=head1 NOTES
5f05dabc 1713
1714=head2 Object Terminology
1715
1716In the various OO literature, it seems that a lot of different words
1717are used to describe only a few different concepts. If you're not
1718already an object programmer, then you don't need to worry about all
1719these fancy words. But if you are, then you might like to know how to
1720get at the same concepts in Perl.
1721
1722For example, it's common to call an object an I<instance> of a class
1723and to call those objects' methods I<instance methods>. Data fields
1724peculiar to each object are often called I<instance data> or I<object
1725attributes>, and data fields common to all members of that class are
1726I<class data>, I<class attributes>, or I<static data members>.
1727
1728Also, I<base class>, I<generic class>, and I<superclass> all describe
1729the same notion, whereas I<derived class>, I<specific class>, and
1730I<subclass> describe the other related one.
1731
1732C++ programmers have I<static methods> and I<virtual methods>,
1733but Perl only has I<class methods> and I<object methods>.
1734Actually, Perl only has methods. Whether a method gets used
1735as a class or object method is by usage only. You could accidentally
1736call a class method (one expecting a string argument) on an
1737object (one expecting a reference), or vice versa.
1738
aaa2bbb1 1739From the C++ perspective, all methods in Perl are virtual.
5f05dabc 1740This, by the way, is why they are never checked for function
54310121 1741prototypes in the argument list as regular builtin and user-defined
5f05dabc 1742functions can be.
1743
1744Because a class is itself something of an object, Perl's classes can be
1745taken as describing both a "class as meta-object" (also called I<object
1746factory>) philosophy and the "class as type definition" (I<declaring>
1747behaviour, not I<defining> mechanism) idea. C++ supports the latter
1748notion, but not the former.
1749
1750=head1 SEE ALSO
1751
54310121 1752The following manpages will doubtless provide more
5f05dabc 1753background for this one:
1754L<perlmod>,
1755L<perlref>,
1756L<perlobj>,
1757L<perlbot>,
1758L<perltie>,
1759and
1760L<overload>.
1761
8257a158 1762L<perlboot> is a kinder, gentler introduction to object-oriented
1763programming.
1764
890a53b9 1765L<perltooc> provides more detail on class data.
8257a158 1766
1767Some modules which might prove interesting are Class::Accessor,
1768Class::Class, Class::Contract, Class::Data::Inheritable,
1769Class::MethodMaker and Tie::SecureHash
1770
1771
5a964f20 1772=head1 AUTHOR AND COPYRIGHT
1773
1774Copyright (c) 1997, 1998 Tom Christiansen
1775All rights reserved.
1776
5a7beb56 1777This documentation is free; you can redistribute it and/or modify it
1778under the same terms as Perl itself.
5f05dabc 1779
5a964f20 1780Irrespective of its distribution, all code examples in this file
1781are hereby placed into the public domain. You are permitted and
1782encouraged to use this code in your own programs for fun
1783or for profit as you see fit. A simple comment in the code giving
1784credit would be courteous but is not required.
1785
1786=head1 COPYRIGHT
5f05dabc 1787
1788=head2 Acknowledgments
1789
1790Thanks to
1791Larry Wall,
1792Roderick Schertler,
1793Gurusamy Sarathy,
1794Dean Roehrich,
1795Raphael Manfredi,
1796Brent Halsey,
1797Greg Bacon,
1798Brad Appleton,
1799and many others for their helpful comments.