3 perltoot - tchrist's object-oriented perl tutorial (rev 0.4)
7 Object-oriented programming is a big seller these days. Some managers
8 would rather have objects than sliced bread. Why is that? What's so
9 special about an object? Just what I<is> an object anyway?
11 An object is nothing but a way of tucking away complex behaviours into
12 a neat little easy-to-use bundle. (This is what professors call
13 abstraction.) Smart people who have nothing to do but sit around for
14 weeks on end figuring out really hard problems make these nifty
15 objects that even regular people can use. (This is what professors call
16 software reuse.) Users (well, programmers) can play with this little
17 bundle all they want, but they aren't to open it up and mess with the
18 insides. Just like an expensive piece of hardware, the contract says
19 that you void the warranty if you muck with the cover. So don't do that.
21 The heart of objects is the class, a protected little private namespace
22 full of data and functions. A class is a set of related routines that
23 addresses some problem area. You can think of it as a user-defined type.
24 The Perl package mechanism, also used for more traditional modules,
25 is used for class modules as well. Objects "live" in a class, meaning
26 that they belong to some package.
28 More often than not, the class provides the user with little bundles.
29 These bundles are objects. They know whose class they belong to,
30 and how to behave. Users ask the class to do something, like "give
31 me an object." Or they can ask one of these objects to do something.
32 Asking a class to do something for you is calling a I<class method>.
33 Asking an object to do something for you is calling an I<object method>.
34 Asking either a class (usually) or an object (sometimes) to give you
35 back an object is calling a I<constructor>, which is just a
36 particular kind of method.
38 That's all well and good, but how is an object different from any other
39 Perl data type? Just what is an object I<really>; that is, what's its
40 fundamental type? The answer to the first question is easy. An object
41 is different from any other data type in Perl in one and only one way:
42 you may dereference it using not merely string or numeric subscripts
43 as with simple arrays and hashes, but with named subroutine calls.
44 In a word, with I<methods>.
46 The answer to the second question is that it's a reference, and not just
47 any reference, mind you, but one whose referent has been I<bless>()ed
48 into a particular class (read: package). What kind of reference? Well,
49 the answer to that one is a bit less concrete. That's because in Perl
50 the designer of the class can employ any sort of reference they'd like
51 as the underlying intrinsic data type. It could be a scalar, an array,
52 or a hash reference. It could even be a code reference. But because
53 of its inherent flexibility, an object is usually a hash reference.
55 =head1 Creating a Class
57 Before you create a class, you need to decide what to name it. That's
58 because the class (package) name governs the name of the file used to
59 house it, just as with regular modules. Then, that class (package)
60 should provide one or more ways to generate objects. Finally, it should
61 provide mechanisms to allow users of its objects to indirectly manipulate
62 these objects from a distance.
64 For example, let's make a simple Person class module. It gets stored in
65 the file Person.pm. If it were called a Happy::Person class, it would
66 be stored in the file Happy/Person.pm, and its package would become
67 Happy::Person instead of just Person. (On a personal computer not
68 running Unix or Plan 9, but something like MacOS or VMS, the directory
69 separator may be different, but the principle is the same.) Do not assume
70 any formal relationship between modules based on their directory names.
71 This is merely a grouping convenience, and has no effect on inheritance,
72 variable accessibility, or anything else.
74 For this module we aren't going to use Exporter, because we're
75 a well-behaved class module that doesn't export anything at all.
76 In order to manufacture objects, a class needs to have a I<constructor
77 method>. A constructor gives you back not just a regular data type,
78 but a brand-new object in that class. This magic is taken care of by
79 the bless() function, whose sole purpose is to enable its referent to
80 be used as an object. Remember: being an object really means nothing
81 more than that methods may now be called against it.
83 While a constructor may be named anything you'd like, most Perl
84 programmers seem to like to call theirs new(). However, new() is not
85 a reserved word, and a class is under no obligation to supply such.
86 Some programmers have also been known to use a function with
87 the same name as the class as the constructor.
89 =head2 Object Representation
91 By far the most common mechanism used in Perl to represent a Pascal
92 record, a C struct, or a C++ class an anonymous hash. That's because a
93 hash has an arbitrary number of data fields, each conveniently accessed by
94 an arbitrary name of your own devising.
96 If you were just doing a simple
97 struct-like emulation, you would likely go about it something like this:
102 peers => [ "Norbert", "Rhys", "Phineas"],
105 If you felt like it, you could add a bit of visual distinction
106 by up-casing the hash keys:
111 PEERS => [ "Norbert", "Rhys", "Phineas"],
114 And so you could get at C<$rec-E<gt>{NAME}> to find "Jason", or
115 C<@{ $rec-E<gt>{PEERS} }> to get at "Norbert", "Rhys", and "Phineas".
116 (Have you ever noticed how many 23-year-old programmers seem to
117 be named "Jason" these days? :-)
119 This same model is often used for classes, although it is not considered
120 the pinnacle of programming propriety for folks from outside the
121 class to come waltzing into an object, brazenly accessing its data
122 members directly. Generally speaking, an object should be considered
123 an opaque cookie that you use I<object methods> to access. Visually,
124 methods look like you're dereffing a reference using a function name
125 instead of brackets or braces.
127 =head2 Class Interface
129 Some languages provide a formal syntactic interface to a class's methods,
130 but Perl does not. It relies on you to read the documentation of each
131 class. If you try to call an undefined method on an object, Perl won't
132 complain, but the program will trigger an exception while it's running.
133 Likewise, if you call a method expecting a prime number as its argument
134 with an even one instead, you can't expect the compiler to catch this.
135 (Well, you can expect it all you like, but it's not going to happen.)
137 Let's suppose you have a well-educated user of you Person class,
138 someone who has read the docs that explain the prescribed
139 interface. Here's how they might use the Person class:
143 $him = Person->new();
146 $him->peers( "Norbert", "Rhys", "Phineas" );
148 push @All_Recs, $him; # save object in array for later
150 printf "%s is %d years old.\n", $him->name, $him->age;
151 print "His peers are: ", join(", ", $him->peers), "\n";
153 printf "Last rec's name is %s\n", $All_Recs[-1]->name;
155 As you can see, the user of the class doesn't know (or at least, has no
156 business paying attention to the fact) that the object has one particular
157 implementation or another. The interface to the class and its objects
158 is exclusively via methods, and that's all the user of the class should
161 =head2 Constructors and Instance Methods
163 Still, I<someone> has to know what's in the object. And that someone is
164 the class. It implements methods that the programmer uses to access
165 the object. Here's how to implement the Person class using the standard
166 hash-ref-as-an-object idiom. We'll make a class method called new() to
167 act as the constructor, and three object methods called name(), age(), and
168 peers() to get at per-object data hidden away in our anonymous hash.
173 ##################################################
174 ## the object constructor (simplistic version) ##
175 ##################################################
178 $self->{NAME} = undef;
179 $self->{AGE} = undef;
181 bless($self); # but see below
185 ##############################################
186 ## methods to access per-object data ##
188 ## With args, they set the value. Without ##
189 ## any, they only retrieve it/them. ##
190 ##############################################
194 if (@_) { $self->{NAME} = shift }
195 return $self->{NAME};
200 if (@_) { $self->{AGE} = shift }
206 if (@_) { @{ $self->{PEERS} } = @_ }
207 return @{ $self->{PEERS} };
210 1; # so the require or use succeeds
212 We've created three methods to access an object's data, name(), age(),
213 and peers(). These are all substantially similar. If called with an
214 argument, they set the appropriate field; otherwise they return the
215 value held by that field, meaning the value of that hash key.
217 =head2 Planning for the Future: Better Constructors
219 Even though at this point you may not even know what it means, someday
220 you're going to worry about inheritance. (You can safely ignore this
221 for now and worry about it later if you'd like.) To ensure that this
222 all works out smoothly, you must use the double-argument form of bless().
223 The second argument is the class into which the referent will be blessed.
224 By not assuming our own class as the default second argument and instead
225 using the class passed into us, we make our constructor inheritable.
227 While we're at it, let's make our constructor a bit more flexible.
228 Rather than being uniquely a class method, we'll set it up so that
229 it can be called as either a class method I<or> an object
230 method. That way you can say:
235 To do this, all we have to do is check whether what was passed in
236 was a reference or not. If so, we were invoked as an object method,
237 and we need to extract the package (class) using the ref() function.
238 If not, we just use the string passed in as the package name
239 for blessing our referent.
243 my $class = ref($proto) || $proto;
245 $self->{NAME} = undef;
246 $self->{AGE} = undef;
248 bless ($self, $class);
252 That's about all there is for constructors. These methods bring objects
253 to life, returning neat little opaque bundles to the user to be used in
254 subsequent method calls.
258 Every story has a beginning and an end. The beginning of the object's
259 story is its constructor, explicitly called when the object comes into
260 existence. But the ending of its story is the I<destructor>, a method
261 implicitly called when an object leaves this life. Any per-object
262 clean-up code is placed in the destructor, which must (in Perl) be called
265 If constructors can have arbitrary names, then why not destructors?
266 Because while a constructor is explicitly called, a destructor is not.
267 Destruction happens automatically via Perl's garbage collection (GC)
268 system, which is a quick but somewhat lazy reference-based GC system.
269 To know what to call, Perl insists that the destructor be named DESTROY.
271 Why is DESTROY in all caps? Perl on occasion uses purely upper-case
272 function names as a convention to indicate that the function will
273 be automatically called by Perl in some way. Others that are called
274 implicitly include BEGIN, END, AUTOLOAD, plus all methods used by
275 tied objects, described in L<perltie>.
277 In really good object-oriented programming languages, the user doesn't
278 care when the destructor is called. It just happens when it's supposed
279 to. In low-level languages without any GC at all, there's no way to
280 depend on this happening at the right time, so the programmer must
281 explicitly call the destructor to clean up memory and state, crossing
282 their fingers that it's the right time to do so. Unlike C++, an
283 object destructor is nearly never needed in Perl, and even when it is,
284 explicit invocation is uncalled for. In the case of our Person class,
285 we don't need a destructor because Perl takes care of simple matters
286 like memory deallocation.
288 The only situation where Perl's reference-based GC won't work is
289 when there's a circularity in the data structure, such as:
291 $this->{WHATEVER} = $this;
293 In that case, you must delete the self-reference manually if you expect
294 your program not to leak memory. While admittedly error-prone, this is
295 the best we can do right now. Nonetheless, rest assured that when your
296 program is finished, its objects' destructors are all duly called.
297 So you are guaranteed that an object I<eventually> gets properly
298 destructed, except in the unique case of a program that never exits.
299 (If you're running Perl embedded in another application, this full GC
300 pass happens a bit more frequently--whenever a thread shuts down.)
302 =head2 Other Object Methods
304 The methods we've talked about so far have either been constructors or
305 else simple "data methods", interfaces to data stored in the object.
306 These are a bit like an object's data members in the C++ world, except
307 that strangers don't access them as data. Instead, they should only
308 access the object's data indirectly via its methods. This is an
309 important rule: in Perl, access to an object's data should I<only>
310 be made through methods.
312 Perl doesn't impose restrictions on who gets to use which methods.
313 The public-versus-private distinction is by convention, not syntax.
314 (Well, unless you use the Alias module described below in L</"Data Members
315 as Variables">.) Occasionally you'll see method names beginning or ending
316 with an underscore or two. This marking is a convention indicating
317 that the methods are private to that class alone and sometimes to its
318 closest acquaintances, its immediate subclasses. But this distinction
319 is not enforced by Perl itself. It's up to the programmer to behave.
321 There's no reason to limit methods to those that simply access data.
322 Methods can do anything at all. The key point is that they're invoked
323 against an object or a class. Let's say we'd like object methods that
324 do more than fetch or set one particular field .
328 return sprintf "Hi, I'm %s, age %d, working with %s",
329 $self->{NAME}, $self->{AGE}, join(", ", $self->{PEERS});
332 Or maybe even one like this:
336 return ++$self->{AGE};
339 Some might argue that one should go at these this way:
343 return sprintf "Hi, I'm %s, age %d, working with %s",
344 $self->name, $self->age, join(", ", $self->peers);
349 return $self->age( $self->age() + 1 );
352 But since these methods are all executing in the class itself, this
353 may not be critical. There are trade-offs to be made. Using direct
354 hash access is faster (about an order of magnitude faster, in fact), and
355 it's more convenient when you want to interpolate in strings. But using
356 methods (the external interface) internally shields not just the users of
357 your class but even you yourself from changes in your data representation.
361 What about "class data", data items common to each object in a class?
362 What would you want that for? Well, in your Person class, you might
363 like to keep track of the total people alive. How do you implement that?
365 You I<could> make it a global variable called $Person::Census. But about
366 only reason you'd do that would be if you I<wanted> people to be able to
367 get at your class data directly. They could just say $Person::Census
368 and play around with it. Maybe this is ok in your design scheme.
369 You might even conceivably want to make it an exported variable. To be
370 exportable, a variable must be a (package) global. If this were a
371 traditional module rather than an object-oriented one, you might do that.
373 While this approach is expected in most traditional modules, it's
374 generally considered rather poor form in most object modules. In an
375 object module, you should set up a protective veil to separate interface
376 from implementation. So provide a class method to access class data
377 just as you provide object methods to access object data.
379 So, you I<could> still keep $Census as a package global and rely upon
380 others to honor the contract of the module and therefore not play around
381 with its implementation. You could even be supertricky and make $Census a
382 tied object as described in L<perltie>, thereby intercepting all accesses.
384 But more often than not, you just want to make your class data a
385 file-scoped lexical. To do so, simply put this at the top of the file:
389 Even though the scope of a my() normally expires when the block in which
390 it was declared is done (in this case the whole file being required or
391 used), Perl's deep binding of lexical variables guarantees that the
392 variable will not be deallocated, remaining accessible to functions
393 declared within that scope. This doesn't work with global variables
394 given temporary values via local(), though.
396 Irrespective of whether you leave $Census a package global or make
397 it instead a file-scoped lexical, you should make these
398 changes to your Person::new() constructor:
402 my $class = ref($proto) || $proto;
405 $self->{NAME} = undef;
406 $self->{AGE} = undef;
408 bless ($self, $class);
416 Now that we've done this, we certainly do need a destructor so that
417 when Person is destroyed, the $Census goes down. Here's how
420 sub DESTROY { --$Census }
422 Notice how there's no memory to deallocate in the destructor? That's
423 something that Perl takes care of for you all by itself.
425 =head2 Accessing Class Data
427 It turns out that this is not really a good way to go about handling
428 class data. A good scalable rule is that I<you must never reference class
429 data directly from an object method>. Otherwise you aren't building a
430 scalable, inheritable class. The object must be the rendezvous point
431 for all operations, especially from an object method. The globals
432 (class data) would in some sense be in the "wrong" package in your
433 derived classes. In Perl, methods execute in the context of the class
434 they were defined in, I<not> that of the object that triggered them.
435 Therefore, namespace visibility of package globals in methods is unrelated
438 Got that? Maybe not. Ok, let's say that some other class "borrowed"
439 (well, inherited) the DESTROY method as it was defined above. When those
440 objects are destructed, the original $Census variable will be altered,
441 not the one in the new class's package namespace. Perhaps this is what
442 you want, but probably it isn't.
444 Here's how to fix this. We'll store a reference to the data in the
445 value accessed by the hash key "_CENSUS". Why the underscore? Well,
446 mostly because an initial underscore already conveys strong feelings
447 of magicalness to a C programmer. It's really just a mnemonic device
448 to remind ourselves that this field is special and not to be used as
449 a public data member in the same way that NAME, AGE, and PEERS are.
450 (Because we've been developing this code under the strict pragma, prior
451 to 5.004 we'll have to quote the field name.)
455 my $class = ref($proto) || $proto;
457 $self->{NAME} = undef;
458 $self->{AGE} = undef;
461 $self->{"_CENSUS"} = \$Census;
462 bless ($self, $class);
463 ++ ${ $self->{"_CENSUS"} };
470 return ${ $self->{"_CENSUS"} };
478 -- ${ $self->{"_CENSUS"} };
481 =head2 Debugging Methods
483 It's common for a class to have a debugging mechanism. For example,
484 you might want to see when objects are created or destroyed. To do that,
485 add a debugging variable as a file-scoped lexical. For this, we'll pull
486 in the standard Carp module to emit our warnings and fatal messages.
487 That way messages will come out with the caller's filename and
488 line number instead of our own; if we wanted them to be from our own
489 perspective, we'd just use die() and warn() directly instead of croak()
490 and carp() respectively.
495 Now add a new class method to access the variable.
499 if (ref $class) { confess "Class method called as object method" }
500 unless (@_ == 1) { confess "usage: CLASSNAME->debug(level)" }
504 Now fix up DESTROY to murmur a bit as the moribund object expires:
508 if ($Debugging) { carp "Destroying $self " . $self->name }
509 -- ${ $self->{"_CENSUS"} };
512 One could conceivably make a per-object debug state. That
513 way you could call both of these:
515 Person->debug(1); # entire class
516 $him->debug(1); # just this object
518 To do so, we need our debugging method to be a "bimodal" one, one that
519 works on both classes I<and> objects. Therefore, adjust the debug()
520 and DESTROY methods as follows:
524 confess "usage: thing->debug(level)" unless @_ == 1;
527 $self->{"_DEBUG"} = $level; # just myself
529 $Debugging = $level; # whole class
535 if ($Debugging || $self->{"_DEBUG"}) {
536 carp "Destroying $self " . $self->name;
538 -- ${ $self->{"_CENSUS"} };
541 =head2 Class Destructors
543 The object destructor handles for each particular object. But sometimes
544 you want a bit of cleanup when the entire class is shut down, which
545 currently only happens when the program exits. To make such a
546 I<class destructor>, create a function in that class's package named
547 END. This works just like the END function in traditional modules,
548 meaning that it gets called whenever your program exits unless it execs
549 or dies of an uncaught signal. For example,
553 print "All persons are going away now.\n";
557 When the program exits, all the class destructors (END functions) are
558 be called in the opposite order that they were loaded in (LIFO order).
560 =head2 Documenting the Interface
562 And there you have it: we've just shown you the I<implementation> of this
563 Person class. Its I<interface> would be its documentation. Usually this
564 means putting it in pod ("plain old documentation") format right there
565 in the same file. In our Person example, we would place the following
566 docs anywhere in the Person.pm file. Even though it looks mostly like
567 code, it's not. It's embedded documentation such as would be used by
568 the pod2man, pod2html, or pod2text programs. The Perl compiler ignores
569 pods entirely, just as the translators ignore code. Here's an example of
570 some pods describing the informal interface:
574 Person - class to implement people
584 $count = Person->population;
586 #######################
587 # object data methods #
588 #######################
598 $ob->peers( "Norbert", "Rhys", "Phineas" );
600 ########################
601 # other object methods #
602 ########################
604 $phrase = $ob->exclaim;
609 The Person class implements dah dee dah dee dah....
611 That's all there is to the matter of interface versus implementation.
612 A programmer who opens up the module and plays around with all the private
613 little shiny bits that were safely locked up behind the interface contract
614 has voided the warranty, and you shouldn't worry about their fate.
618 Suppose you later want to change the class to implement better names.
619 Perhaps you'd like to support both given names (called Christian names,
620 irrespective of one's religion) and family names (called surnames), plus
621 nicknames and titles. If users of your Person class have been properly
622 accessing it through its documented interface, then you can easily change
623 the underlying implementation. If they haven't, then they lose and
624 it's their fault for breaking the contract and voiding their warranty.
626 To do this, we'll make another class, this one called Fullname. What's
627 the Fullname class look like? To answer that question, you have to
628 first figure out how you want to use it. How about we use it this way:
630 $him = Person->new();
631 $him->fullname->title("St");
632 $him->fullname->christian("Thomas");
633 $him->fullname->surname("Aquinas");
634 $him->fullname->nickname("Tommy");
635 printf "His normal name is %s\n", $him->name;
636 printf "But his real name is %s\n", $him->fullname->as_string;
638 Ok. To do this, we'll change Person::new() so that it supports
639 a full name field this way:
643 my $class = ref($proto) || $proto;
645 $self->{FULLNAME} = Fullname->new();
646 $self->{AGE} = undef;
648 $self->{"_CENSUS"} = \$Census;
649 bless ($self, $class);
650 ++ ${ $self->{"_CENSUS"} };
656 return $self->{FULLNAME};
659 Then to support old code, define Person::name() this way:
663 return $self->{FULLNAME}->nickname(@_)
664 || $self->{FULLNAME}->christian(@_);
667 Here's the Fullname class. We'll use the same technique
668 of using a hash reference to hold data fields, and methods
669 by the appropriate name to access them:
676 my $class = ref($proto) || $proto;
683 bless ($self, $class);
689 if (@_) { $self->{CHRISTIAN} = shift }
690 return $self->{CHRISTIAN};
695 if (@_) { $self->{SURNAME} = shift }
696 return $self->{SURNAME};
701 if (@_) { $self->{NICK} = shift }
702 return $self->{NICK};
707 if (@_) { $self->{TITLE} = shift }
708 return $self->{TITLE};
713 my $name = join(" ", @$self{'CHRISTIAN', 'SURNAME'});
714 if ($self->{TITLE}) {
715 $name = $self->{TITLE} . " " . $name;
722 Finally, here's the test program:
727 sub END { show_census() }
730 printf "Current population: %d\n", Person->population;
737 my $him = Person->new();
739 $him->fullname->christian("Thomas");
740 $him->fullname->surname("Aquinas");
741 $him->fullname->nickname("Tommy");
742 $him->fullname->title("St");
745 printf "%s is really %s.\n", $him->name, $him->fullname;
746 printf "%s's age: %d.\n", $him->name, $him->age;
747 $him->happy_birthday;
748 printf "%s's age: %d.\n", $him->name, $him->age;
754 Object-oriented programming systems all support some notion of
755 inheritance. Inheritance means allowing one class to piggy-back on
756 top of another one so you don't have to write the same code again and
757 again. It's about software reuse, and therefore related to Laziness,
758 the principal virtue of a programmer. (The import/export mechanisms in
759 traditional modules are also a form of code reuse, but a simpler one than
760 the true inheritance that you find in object modules.)
762 Sometimes the syntax of inheritance is built into the core of the
763 language, and sometimes it's not. Perl has no special syntax for
764 specifying the class (or classes) to inherit from. Instead, it's all
765 strictly in the semantics. Each package can have a variable called @ISA,
766 which governs (method) inheritance. If you try to call a method on an
767 object or class, and that method is not found in that object's package,
768 Perl then looks to @ISA for other packages to go looking through in
769 search of the missing method.
771 Like the special per-package variables recognized by Exporter (such as
772 @EXPORT, @EXPORT_OK, @EXPORT_FAIL, %EXPORT_TAGS, and $VERSION), the @ISA
773 array I<must> be a package-scoped global and not a file-scoped lexical
774 created via my(). Most classes have just one item in their @ISA array.
775 In this case, we have what's called "single inheritance", or SI for short.
784 Not a lot to it, eh? All it's doing so far is loading in another
785 class and stating that this one will inherit methods from that
786 other class if need be. We have given it none of its own methods.
787 We rely upon an Employee to behave just like a Person.
789 Setting up an empty class like this is called the "empty subclass test";
790 that is, making a derived class that does nothing but inherit from a
791 base class. If the original base class has been designed properly,
792 then the new derived class can be used as a drop-in replacement for the
793 old one. This means you should be able to write a program like this:
796 my $empl = Employee->new();
797 $empl->name("Jason");
799 printf "%s is age %d.\n", $empl->name, $empl->age;
801 By proper design, we mean always using the two-argument form of bless(),
802 avoiding direct access of global data, and not exporting anything. If you
803 look back at the Person::new() function we defined above, we were careful
804 to do that. There's a bit of package data used in the constructor,
805 but the reference to this is stored on the object itself and all other
806 methods access package data via that reference, so we should be ok.
808 What do we mean by the Person::new() function -- isn't that actually
809 method. Well, in principle, yes. A method is just a function that
810 expects as its first argument a class name (package) or object
811 (bless reference). Person::new() is the function that both the
812 C<Person-E<gt>new()> method and the C<Employee-E<gt>new()> method end
813 up calling. Understand that while a method call looks a lot like a
814 function call, they aren't really quite the same, and if you treat them
815 as the same, you'll very soon be left with nothing but broken programs.
816 First, the actual underlying calling conventions are different: method
817 calls get an extra argument. Second, function calls don't do inheritance,
820 Method Call Resulting Function Call
821 ----------- ------------------------
822 Person->new() Person::new("Person")
823 Employee->new() Person::new("Employee")
825 So don't use function calls when you mean to call a method.
827 If an employee is just a Person, that's not all too very interesting.
828 So let's add some other methods. We'll give our employee
829 data fields to access their salary, their employee ID, and their
832 If you're getting a little tired of creating all these nearly identical
833 methods just to get at the object's data, do not despair. Later,
834 we'll describe several different convenience mechanisms for shortening
835 this up. Meanwhile, here's the straight-forward way:
839 if (@_) { $self->{SALARY} = shift }
840 return $self->{SALARY};
845 if (@_) { $self->{ID} = shift }
851 if (@_) { $self->{START_DATE} = shift }
852 return $self->{START_DATE};
855 =head2 Overridden Methods
857 What happens when both a derived class and its base class have the same
858 method defined? Well, then you get the derived class's version of that
859 method. For example, let's say that we want the peers() method called on
860 an employee to act a bit differently. Instead of just returning the list
861 of peer names, let's return slightly different strings. So doing this:
863 $empl->peers("Peter", "Paul", "Mary");
864 printf "His peers are: %s\n", join(", ", $empl->peers);
868 His peers are: PEON=PETER, PEON=PAUL, PEON=MARY
870 To do this, merely add this definition into the Employee.pm file:
874 if (@_) { @{ $self->{PEERS} } = @_ }
875 return map { "PEON=\U$_" } @{ $self->{PEERS} };
878 There, we've just demonstrated the high-falutin' concept known in certain
879 circles as I<polymorphism>. We've taken on the form and behavior of
880 an existing object, and then we've altered it to suit our own purposes.
881 This is a form of Laziness. (Getting polymorphed is also what happens
882 when the wizard decides you'd look better as a frog.)
884 Every now and then you'll want to have a method call trigger both its
885 derived class (also know as "subclass") version as well as its base class
886 (also known as "superclass") version. In practice, constructors and
887 destructors are likely to want to do this, and it probably also makes
888 sense in the debug() method we showed previously.
890 To do this, add this to Employee.pm:
897 confess "usage: thing->debug(level)" unless @_ == 1;
900 $self->{"_DEBUG"} = $level;
902 $Debugging = $level; # whole class
904 Person::debug($self, $Debugging); # don't really do this
907 As you see, we turn around and call the Person package's debug() function.
908 But this is far too fragile for good design. What if Person doesn't
909 have a debug() function, but is inheriting I<its> debug() method
910 from elsewhere? It would have been slightly better to say
912 Person->debug($Debugging);
914 But even that's got too much hard-coded. It's somewhat better to say
916 $self->Person::debug($Debugging);
918 Which is a funny way to say to start looking for a debug() method up
919 in Person. This strategy is more often seen on overridden object methods
920 than on overridden class methods.
922 There is still something a bit off here. We've hard-coded our
923 superclass's name. This in particular is bad if you change which classes
924 you inherit from, or add others. Fortunately, the pseudoclass SUPER
925 comes to the rescue here.
927 $class->SUPER::debug($Debugging);
929 This way it starts looking in my class's @ISA. This only makes sense
930 from I<within> a method call, though. Don't try to access anything
931 in SUPER:: from anywhere else, because it doesn't exist outside
932 an overridden method call.
934 Things are getting a bit complicated here. Have we done anything
935 we shouldn't? As before, one way to test whether we're designing
936 a decent class is via the empty subclass test. Since we already have
937 an Employee class that we're trying to check, we'd better get a new
938 empty subclass that can derive from Employee. Here's one:
944 And here's the test program:
951 my $boss = Boss->new();
953 $boss->fullname->title("Don");
954 $boss->fullname->surname("Pichon Alvarez");
955 $boss->fullname->christian("Federico Jesus");
956 $boss->fullname->nickname("Fred");
959 $boss->peers("Frank", "Felipe", "Faust");
961 printf "%s is age %d.\n", $boss->fullname, $boss->age;
962 printf "His peers are: %s\n", join(", ", $boss->peers);
964 Running it, we see that we're still ok. If you'd like to dump out your
965 object in a nice format, the way the 'x' command does in the debugger,
966 you could use these undocumented calls the debugger employs (until
967 its author changes them).
969 require 'dumpvar.pl';
970 print "Here's the boss:\n";
973 Which shows us something like this:
976 '_CENSUS' => SCALAR(0x80c949c)
979 'FULLNAME' => Fullname=HASH(0x81040d8)
980 'CHRISTIAN' => 'Federico Miguel'
982 'SURNAME' => 'Pichon Alvarez'
984 'PEERS' => ARRAY(0x80ebb3c)
989 Hm.... something's missing there. What about the salary, start date,
990 and ID fields? Well, we never set them to anything, even undef, so they
991 don't show up in the hash's keys. The Employee class has no new() method
992 of its own, and the new() method in Person doesn't know about Employees.
993 (Nor should it: proper OO design dictates that a subclass be allowed to
994 know about its immediate superclass, but never vice-versa.) So let's
995 fix up Employee::new() this way:
999 my $class = ref($proto) || $proto;
1000 my $self = $class->SUPER::new();
1001 $self->{SALARY} = undef;
1002 $self->{ID} = undef;
1003 $self->{START_DATE} = undef;
1004 bless ($self, $class); # reconsecrate
1008 Now if you dump out an Employee or Boss object, you'll find
1009 that new fields show up there now.
1011 =head2 Multiple Inheritance
1013 Ok, at the risk of confusing beginners and annoying OO gurus, it's
1014 time to confess that Perl's object system includes that controversial
1015 notion known as multiple inheritance, or MI for short. All this means
1016 is that rather than having just one parent class who in turn might
1017 itself have a parent class, etc., that you can directly inherit from
1018 two or more parents. It's true that some uses of MI can get you into
1019 trouble, although hopefully not quite so much trouble with Perl as with
1020 dubiously-OO languages like C++.
1022 The way it works is actually pretty simple: just put more than one package
1023 name in your @ISA array. When it comes time for Perl to go finding
1024 methods for your object, it looks at each of these packages in order.
1025 Well, kinda. It's actually a fully recursive, depth-first order.
1026 Consider a bunch of @ISA arrays like this:
1028 @First::ISA = qw( Alpha );
1029 @Second::ISA = qw( Beta );
1030 @Third::ISA = qw( First Second );
1032 If you have an object of class Third:
1034 my $ob = Third->new();
1037 How do we find a spin() method (or a new() method for that matter)?
1038 Because the search is depth-first, classes will be looked up
1039 in the following order: Third, First, Alpha, Second, and Beta.
1041 In practice, few class modules have been seen that actually
1042 make use of MI. One nearly always chooses simple containership of
1043 one class within another over MI. That's why our Person
1044 object I<contained> a Fullname object. That doesn't mean
1047 However, there is one particular area where MI in Perl is rampant:
1048 borrowing another class's class methods. This is rather common,
1049 particularly with some bundled "objectless" classes,
1050 like Exporter, DynaLoader, AutoLoader, and SelfLoader. These classes
1051 do not provide constructors; they exist only so you may inherit their
1052 class methods. (It's not entirey clear why inheritance was done
1053 here rather than traditional module importation.)
1055 For example, here is the POSIX module's @ISA:
1058 @ISA = qw(Exporter DynaLoader);
1060 The POSIX module isn't really an object module, but then,
1061 neither are Exporter or DynaLoader. They're just lending their
1062 classes' behaviours to POSIX.
1064 Why don't people use MI for object methods much? One reason is that
1065 it can have complicated side-effects. For one thing, your inheritance
1066 graph (no longer a tree) might converge back to the same base class.
1067 Although Perl guards against recursive inheritance, but having parents
1068 who are related to each other via a common ancestor, incestuous though
1069 it sounds, is not forbidden. What if in our Third class shown above we
1070 wanted its new() method to also call both overridden constructors in its
1071 two parent classes? The SUPER notation would only find the first one.
1072 Also, what about if the Alpha and Beta classes both had a common ancestor,
1073 like Nought? If you kept climbing up the inheritance tree calling
1074 overridden methods, you'd end up calling Nought::new() twice,
1075 which might well be a bad idea.
1077 =head2 UNIVERSAL: The Root of All Objects
1079 Wouldn't it be convenient if all objects were rooted at some ultimate
1080 base class? That way you could give every object common methods without
1081 having to go and add it to each and every @ISA. Well, it turns out that
1082 you can. You don't see it, but Perl tacitly and irrevocably assumes
1083 that there's an extra element at the end of @ISA: the class UNIVERSAL.
1084 In 5.003, there were no predefined methods there, but you could put
1085 whatever you felt like into it.
1087 However, as of 5.004 (or some subversive releases, like 5.003_08),
1088 UNIVERSAL has some methods in it already. These are built-in to your Perl
1089 binary, so they don't take any extra time to load. Predefined methods
1090 include isa(), can(), and VERSION(). isa() tells you whether an object or
1091 class "is" another one without having to traverse the hierarchy yourself:
1093 $has_io = $fd->isa("IO::Handle");
1094 $itza_handle = IO::Socket->isa("IO::Handle");
1096 The can() method, called against that object or class, reports back
1097 whether its string argument is a callable method name in that class.
1098 In fact, it gives you back a function reference to that method:
1100 $his_print_method = $obj->can('as_string');
1102 Finally, the VERSION method checks whether the class (or the object's
1103 class) has a package global called $VERSION that's high enough, as in:
1105 Some_Module->VERSION(3.0);
1106 $his_vers = $ob->VERSION();
1108 However, we don't usually call VERSION ourselves. (Remember that an all
1109 upper-case function name is a Perl convention that indicates that the
1110 function will be automatically used by Perl in some way.) In this case,
1111 it happens when you say
1113 use Some_Module 3.0;
1115 If you wanted to add versioning to your Person class explained
1116 above, just add this to Person.pm:
1118 use vars qw($VERSION);
1121 and then in Employee.pm could you can say
1125 And it would make sure that you have at least that version number or
1126 higher available. This is not the same as loading in that exact version
1127 number. No mechanism currently exists for concurrent installation of
1128 multiple versions of a module. Lamentably.
1130 =head1 Alternate Object Representations
1132 Nothing requires objects to be implemented as hash references. An object
1133 can be any sort of reference so long as its referent has been suitably
1134 blessed. That means scalar, array, and code references are also fair
1137 A scalar would work if the object has only one datum to hold. An array
1138 would work for most cases, but makes inheritance a bit dodgy because
1139 you have to invent new indices for the derived classes.
1141 =head2 Arrays as Objects
1143 If the user of your class honors the contract and sticks to the advertised
1144 interface, then you can change its underlying interface if you feel
1145 like it. Here's another implementation that conforms to the same
1146 interface specification. This time we'll use an array reference
1147 instead of a hash reference to represent the object.
1152 my($NAME, $AGE, $PEERS) = ( 0 .. 2 );
1154 ############################################
1155 ## the object constructor (array version) ##
1156 ############################################
1159 $self->[$NAME] = undef; # this is unnecessary
1160 $self->[$AGE] = undef; # as it this
1161 $self->[$PEERS] = []; # but this isn't, really
1168 if (@_) { $self->[$NAME] = shift }
1169 return $self->[$NAME];
1174 if (@_) { $self->[$AGE] = shift }
1175 return $self->[$AGE];
1180 if (@_) { @{ $self->[$PEERS] } = @_ }
1181 return @{ $self->[$PEERS] };
1184 1; # so the require or use succeeds
1186 You might guess that the array access will be a lot faster than the
1187 hash access, but they're actually comparable. The array is a little
1188 bit faster, but not more than ten or fifteen percent, even when you
1189 replace the variables above like $AGE with literal numbers, like 1.
1190 A bigger difference between the two approaches can be found in memory use.
1191 A hash representation takes up more memory than an array representation
1192 because you have to allocation memory for the keys as well as the values.
1193 However, it really isn't that bad, especially since as of 5.004,
1194 memory is only allocated one for a given hash key, no matter how many
1195 hashes have that key. It's expected that sometime in the future, even
1196 these differences will fade into obscurity as more efficient underlying
1197 representations are devised.
1199 Still, the tiny edge in speed (and somewhat larger one in memory)
1200 is enough to make some programmers choose an array representation
1201 for simple classes. There's still a little problem with
1202 scalability, though, because later in life when you feel
1203 like creating subclasses, you'll find that hashes just work
1206 =head2 Closures as Objects
1208 Using a code reference to represent an object offers some fascinating
1209 possibilities. We can create a new anonymous function (closure) who
1210 alone in all the world can see the object's data. This is because we
1211 put the data into an anonymous hash that's lexically visible only to
1212 the closure we create, bless, and return as the object. This object's
1213 methods turn around and call the closure as a regular subroutine call,
1214 passing it as a particular argument the field we want to affect. (Yes,
1215 the double-function call is slow, but if you wanted fast, you wouldn't
1216 be using objects at all, eh? :-)
1218 Use would be similar to before:
1221 $him = Person->new();
1222 $him->name("Jason");
1224 $him->peers( [ "Norbert", "Rhys", "Phineas" ] );
1225 printf "%s is %d years old.\n", $him->name, $him->age;
1226 print "His peers are: ", join(", ", @{$him->peers}), "\n";
1228 but the implementation would be radically, perhaps even sublimely
1235 my $class = ref($that) || $that;
1243 if (@_) { $self->{$field} = shift }
1244 return $self->{$field};
1246 bless($closure, $class);
1250 sub name { &{ $_[0] }("NAME", @_[ 1 .. $#_ ] ) }
1251 sub age { &{ $_[0] }("AGE", @_[ 1 .. $#_ ] ) }
1252 sub peers { &{ $_[0] }("PEERS", @_[ 1 .. $#_ ] ) }
1256 Because this object is hidden behind a code reference, it's probably a bit
1257 mysterious to those whose background is more firmly rooted in standard
1258 procedural or object-based programming languages than in functional
1259 procedural programming languages whence closures derive. The object
1260 created and returned by the new() method is itself not a data reference
1261 as we've seen before. It's an anonymous code reference that has within
1262 it access to a particular version (lexical binding and instantiation)
1263 of the object's data, which are stored in the private variable $self.
1264 Although this is the same function each time, it contains a different
1267 When a method like C<$him-E<gt>name("Jason") is called, its implicit
1268 zeroth argument is as the invoking object just as it is with all method
1269 calls. But in this case, it's our code reference (something like a
1270 function pointer in C++, but with deep binding of lexical variables).
1271 There's not a lot to be done with a code reference beyond calling it, so
1272 that's just what we do when we say C<&{$_[0]}>. This is just a regular
1273 function call, not a method call. The initial argument is the string
1274 "NAME", and any remaining arguments are whatever had been passed to the
1277 Once we're executing inside the closure that had been created in new(),
1278 the $self hash reference suddenly becomes visible. The closure grabs
1279 its first argument ("NAME" in this case because that's what the name()
1280 method passed it), and uses that string to subscript into the private
1281 hash hidden in its unique version of $self.
1283 Nothing under the sun will allow anyone outside the executing method to
1284 be able to get at this hidden data. Well, nearly nothing. You I<could>
1285 single step through the program using the debugger and find out the
1286 pieces while you're in the method, but everyone else is out of luck.
1288 There, if that doesn't excite the Scheme folks, then I just don't know
1289 what will. Translation of this technique into C++, Java, or any other
1290 braindead-static language is left as a futile exercise for aficionados
1293 You could even add a bit of nosiness via the caller() function and
1294 make the closure refuse to operate unless called via its own package.
1295 This would no doubt satisfy certain fastidious concerns of programming
1296 police and related puritans.
1298 If you were wondering when Hubris, the third principle virtue of a
1299 programmer, would come into play, here you have it. (More seriously,
1300 Hubris is just the pride in craftsmanship that comes from having written
1301 a sound bit of well-designed code.)
1303 =head1 AUTOLOAD: Proxy Methods
1305 Autoloading is a way to intercept calls to undefined methods. An autoload
1306 routine may choose to create a new function on the fly, either loaded
1307 from disk or perhaps just eval()ed right there. This define-on-the-fly
1308 strategy is why it's called autoloading.
1310 But that's only one possible approach. Another one is to just
1311 have the autoloaded method itself directly provide the
1312 requested service. When used in this way, you may think
1313 of autoloaded methods as "proxy" methods.
1315 When Perl tries to call an undefined function is a particular package
1316 and that function is not defined, it looks for a function in
1317 that same package called AUTOLOAD. If one exists, it's called
1318 with the same arguments as the original function would have had.
1319 The fully-qualified name of the function is stored in that package's
1320 global variable $AUTOLOAD. Once called, the function can do anything
1321 it would like, including defining a new function by the right name, and
1322 then doing a really fancy kind of C<goto> right to it, erasing itself
1323 from the call stack.
1325 What does this have to do with objects? After all, we keep talking about
1326 functions, not methods. Well, since a method is just a function with
1327 an extra argument and some fancier semantics about where it's found,
1328 we can use autoloading for methods, too. Perl doesn't start looking
1329 for an AUTOLOAD method until it has exhausted the recursive hunt up
1330 through @ISA, though. Some programmers have even been known to define
1331 a UNIVERSAL::AUTOLOAD method to trap unresolved method calls to any
1334 =head2 Autoloaded Data Methods
1336 You probably began to get a little suspicious about the duplicated
1337 code way back earlier when we first showed you the Person class, and
1338 then later the Employee class. Each method used to access the
1339 hash fields looked virtually identical. This should have tickled
1340 that great programming virtue, Impatience, but for the time,
1341 we let Laziness win out, and so did nothing. Proxy methods can cure
1344 Instead of writing a new function every time we want a new data field,
1345 we'll use the autoload mechanism to generate (actually, mimic) methods on
1346 the fly. To verify that we're accessing a valid member, we will check
1347 against an C<_permitted> (pronounced "under-permitted") field, which
1348 is a reference to a file-static hash of permitted fields in this record
1349 called %fields. Why the underscore? For the same reason as the _CENSUS
1350 field we once used: as a marker that means "for internal use only".
1352 Here's what the module initialization code and class
1353 constructor will look like when taking this approach:
1357 use vars qw($AUTOLOAD); # it's a package global
1367 my $class = ref($that) || $that;
1369 _permitted => \%fields,
1372 bless $self, $class;
1376 If we wanted our record to have default values, we could fill those in
1377 where current we have C<undef> in the %fields hash.
1379 Notice how we saved a reference to our class data on the object itself?
1380 Remember that it's important to access class data through the object
1381 itself instead of having any method reference %fields directly, or else
1382 you won't have a decent inheritance.
1384 The real magic, though, is going to reside in our proxy method, which
1385 will handle all calls to undefined methods for objects of class Person
1386 (or subclasses of Person). It has to be called AUTOLOAD. Again, it's
1387 all caps because it's called for us implicitly by Perl itself, not by
1392 my $type = ref($self)
1393 or croak "$self is not an object";
1395 my $name = $AUTOLOAD;
1396 $name =~ s/.*://; # strip fully-qualified portion
1398 unless (exists $self->{_permitted}->{$name} ) {
1399 croak "Can't access `$name' field in class $type";
1403 return $self->{$name} = shift;
1405 return $self->{$name};
1409 Pretty nifty, eh? All we have to do to add new data fields
1410 is modify %fields. No new functions need be written.
1412 =head2 Inherited Autoloaded Data Methods
1414 But what about inheritance? Can we define our Employee
1415 class similarly? Yes, so long as we're careful enough.
1417 Here's how to be careful:
1432 my $class = ref($that) || $that;
1433 my $self = bless $that->SUPER::new(), $class;
1435 foreach $element (keys %fields) {
1436 $self->{_permitted}->{$element} = $fields{$element};
1438 @{$self}{keys %fields} = values %fields;
1442 Once we've done this, we don't even need to have an
1443 AUTOLOAD function in the Employee package, because
1444 we'll grab Person's version of that via inheritance,
1445 and it will all work out just fine.
1447 =head1 Metaclass Tools
1449 Even though proxy methods can provide a more convenient approach to making
1450 more struct-like classes than tediously coding up data methods as
1451 functions, it still leaves a bit to be desired. For one thing, it means
1452 you have to handle bogus calls that you don't mean to trap via your proxy.
1453 It also means you have to be quite careful when dealing with inheritance,
1456 Perl programmers have responded to this by creating several different
1457 class construction classes. These metaclasses are classes
1458 that create other classes. Three worth looking at are
1459 Class::Template, Class::MethodMaker, and Alias. All can be
1460 found in the modules directory on CPAN.
1462 =head2 Class::Template
1464 One of the older ones is Class::Template. In fact, its syntax and
1465 interface were sketched out long before perl5 even solidified into a
1466 real thing. What it does is provide you a way to "declare"
1467 a class as having objects whose fields are of a particular type.
1468 The function that does this is called, not surprisingly
1471 Here's a simple example of using it:
1473 use Class::Template qw(struct);
1474 use Jobbie; # user-defined; see below
1479 profession => Jobbie, # calls Jobbie->new()
1485 $ob->many(0, "here");
1486 $ob->many(1, "you");
1488 print "Just set: ", $ob->many(2), "\n";
1490 $ob->profession->salary(10_000);
1492 You can declare types in the struct to be basic Perl types, or
1493 user-defined types (classes). User types will be initialized by calling
1494 that class's new() method.
1496 Here's a real-world example of using struct generation. Let's say you
1497 wanted to override Perl's idea of gethostbyname() and gethostbyaddr() so
1498 that they would return objects that acted like C structures. We don't
1499 care about high-falutin' OO gunk. All we want is for these objects to
1500 act like structs in the C sense.
1504 $h = gethostbyname("perl.com"); # object return
1505 printf "perl.com's real name is %s, address %s\n",
1506 $h->name, inet_ntoa($h->addr);
1508 Here's how to do this using the Class::Template module.
1509 They crux is going to be this call:
1511 struct 'Net::hostent' => [
1519 Which creates object methods of those names and types.
1520 It even creates a new() method for us.
1522 We could also have implemented our object this way:
1524 struct 'Net::hostent' => {
1532 and then Class::Template would have used an anonymous hash as the object
1533 type, instead of an anonymous array. The array is faster and smaller,
1534 but the hash works out better if you eventually want to do inheritance.
1535 Since for this struct-like object we aren't planning on inheritance,
1536 we'll go for better speed and size over better flexibility.
1538 Here's the whole implementation:
1540 package Net::hostent;
1545 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
1546 @ISA = qw(Exporter);
1547 @EXPORT = qw(gethostbyname gethostbyaddr gethost);
1550 $h_addrtype $h_length
1551 @h_addr_list $h_addr
1553 %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
1555 use vars @EXPORT_OK;
1557 use Class::Template qw(struct);
1558 struct 'Net::hostent' => [
1566 sub addr { shift->addr_list->[0] }
1570 my $hob = new(); # Class::Template made this!
1571 $h_name = $hob->[0] = $_[0];
1572 @h_aliases = @{ $hob->[1] } = split ' ', $_[1];
1573 $h_addrtype = $hob->[2] = $_[2];
1574 $h_length = $hob->[3] = $_[3];
1576 @h_addr_list = @{ $hob->[4] } = @_[ (4 .. $#_) ];
1580 sub gethostbyname ($) { populate(CORE::gethostbyname(shift)) }
1582 sub gethostbyaddr ($;$) {
1583 my ($addr, $addrtype);
1585 require Socket unless @_;
1586 $addrtype = @_ ? shift : Socket::AF_INET();
1587 populate(CORE::gethostbyaddr($addr, $addrtype))
1591 if ($_[0] =~ /^\d+(?:\.\d+(?:\.\d+(?:\.\d+)?)?)?$/) {
1593 &gethostbyaddr(Socket::inet_aton(shift));
1601 We've snuck in quite a fair bit of other concepts besides just dynamic
1602 class creation, like overriding core functions, import/export bits,
1603 function prototyping, and short-cut function call via C<&whatever>.
1604 These all mostly make sense from the perspective of a traditional module,
1605 but as you can see, we can also use them in an object module.
1607 You can look at other object-based, struct-like overrides of core
1608 functions in the 5.004 release of Perl in File::stat, Net::hostent,
1609 Net::netent, Net::protoent, Net::servent, Time::gmtime, Time::localtime,
1610 User::grent, and User::pwent. These modules have a final component
1611 that's all lower-case, by convention reserved for compiler pragmas,
1612 because they affect the compilation and change a built-in function.
1613 They also have the type name that a C programmer would most expect.
1615 =head2 Data Members as Variables
1617 If you're used to C++ objects, then you're accustomed to being able to
1618 get at an object's data members as simple variables from within a method.
1619 The Alias module provides for this, as well as a good bit more, such
1620 as the possibility of private methods that the object can call but folks
1621 outside the class cannot.
1623 Here's an example of creating a Person using the Alias module.
1624 When you update these magical instance variables, you automatically
1625 update value fields in the hash. Convenient, eh?
1629 # this is the same as before...
1632 my $class = ref($that) || $that;
1638 bless($self, $class);
1643 use vars qw($NAME $AGE $PEERS);
1646 my $self = attr shift;
1647 if (@_) { $NAME = shift; }
1652 my $self = attr shift;
1653 if (@_) { $AGE = shift; }
1658 my $self = attr shift;
1659 if (@_) { @PEERS = @_; }
1664 my $self = attr shift;
1665 return sprintf "Hi, I'm %s, age %d, working with %s",
1666 $NAME, $AGE, join(", ", @PEERS);
1669 sub happy_birthday {
1670 my $self = attr shift;
1674 The need for the C<use vars> declaration is because what Alias does
1675 is play with package globals with the same name as the fields. To use
1676 globals while C<use strict> is in effect, you have to pre-declare them.
1677 These package variables are localized to the block enclosing the attr()
1678 call just as if you'd used a local() on them. However, that means that
1679 they're still considered global variables with temporary values, just
1680 as with any other local().
1682 It would be nice to combine Alias with
1683 something like Class::Template or Class::MethodMaker.
1687 =head2 Object Terminology
1689 In the various OO literature, it seems that a lot of different words
1690 are used to describe only a few different concepts. If you're not
1691 already an object programmer, then you don't need to worry about all
1692 these fancy words. But if you are, then you might like to know how to
1693 get at the same concepts in Perl.
1695 For example, it's common to call an object an I<instance> of a class
1696 and to call those objects' methods I<instance methods>. Data fields
1697 particular to each object are often called I<instance data> or <object
1698 attributes>, and data fields common to all members of that class are
1699 I<class data>, I<class attributes>, or I<static data members>.
1701 Also, I<base class>, I<generic class>, and I<subclass> all describe
1702 the same notion, whereas I<derived class>, I<specific class>, and
1703 I<superclass> describe the other related one.
1705 C++ programmers have I<static methods> and I<virtual methods>,
1706 but Perl only has I<class methods> and I<object methods>.
1707 Actually, Perl only has methods. Whether a method gets used
1708 as a class or object method is by usage only. You could accidentally
1709 call a class method (one expecting a string argument) on an
1710 object (one expecting a reference), or vice versa.
1712 >From the C++ perspective, all methods in Perl are virtual.
1713 This, by the way, is why they are never checked for function
1714 prototypes in the argument list as regular built-in and user-defined
1717 Because a class is itself something of an object, Perl's classes can be
1718 taken as describing both a "class as meta-object" (also called I<object
1719 factory>) philosophy and the "class as type definition" (I<declaring>
1720 behavior, not I<defining> mechanism) idea. C++ supports the latter
1721 notion, but not the former.
1723 =head2 Programming with Style
1725 Remember the underscores we used on "start_date" and "START_DATE"?
1726 While some programmers might be tempted to leave them out, please don't.
1727 Otherwise it's hard for some people to read. Also, you'd have to make
1728 up a new rule for identifiers that you've rendered in all capitals,
1729 like START_DATE. Plus you get people wondering whether it's "startdate",
1730 "Startdate", "startDate", "StartDate", or some other crazy variation.
1731 And adding another word, like "employee_start_date", just racks up the
1732 confusion. Nobody but a compiler wants to parse "employeestartdate" or
1733 even "EmployeeStartDate". So (almost) always use underscores to separate
1734 words in identifiers. See also L<perlstyle> and either L<perlmod> or the
1735 list of registered modules posted periodically to comp.lang.perl.modules
1736 or found on CPAN in the http://www.perl.com/CPAN/modules/ directory.
1740 The following man pages will doubtless provide more
1741 background for this one:
1752 I I<really> hate to have to say this, but recent unpleasant
1753 experiences have mandated its inclusion:
1755 Copyright 1996 Tom Christiansen. All Rights Reserved.
1757 This work derives in part from the second edition of I<Programming Perl>.
1758 Although destined for release as a man page with the standard Perl
1759 distribution, it is not public domain (nor is any of Perl and its docset:
1760 publishers beware). It's expected to someday make its way into a revision
1761 of the Camel Book. While it is copyright by me with all rights reserved,
1762 permission is granted to freely distribute verbatim copies of this
1763 document provided that no modifications outside of formatting be made,
1764 and that this notice remain intact. You are permitted and encouraged to
1765 use its code and derivatives thereof in your own source code for fun or
1766 for profit as you see fit. But so help me, if in six months I find some
1767 book out there with a hacked-up version of this material in it claiming to
1768 be written by someone else, I'll tell all the world that you're a jerk.
1769 Furthermore, your lawyer will meet my lawyer (or O'Reilly's) over lunch
1770 to arrange for you to receive your just deserts. Count on it.
1772 =head2 Acknowledgments
1774 Thanks to Brad Appleton, Raphael Manfredi, Dean Roehrich, Gurusamy
1775 Sarathy, and many others from the perl porters list for their helpful