cdd1e02817e210e77e7389f45d8e5e19500731a4
[p5sagit/p5-mst-13.2.git] / pod / perlboot.pod
1 =head1 NAME
2
3 perlboot - Beginner's Object-Oriented Tutorial
4
5 =head1 DESCRIPTION
6
7 If you're not familiar with objects from other languages, some of the
8 other Perl object documentation may be a little daunting, such as
9 L<perlobj>, a basic reference in using objects, and L<perltoot>, which
10 introduces readers to the peculiarities of Perl's object system in a
11 tutorial way.
12
13 So, let's take a different approach, presuming no prior object
14 experience. It helps if you know about subroutines (L<perlsub>),
15 references (L<perlref> et. seq.), and packages (L<perlmod>), so become
16 familiar with those first if you haven't already.
17
18 =head2 If we could talk to the animals...
19
20 Let's let the animals talk for a moment:
21
22     sub Cow::speak {
23       print "a Cow goes moooo!\n";
24     }
25     sub Horse::speak {
26       print "a Horse goes neigh!\n";
27     }
28     sub Sheep::speak {
29       print "a Sheep goes baaaah!\n";
30     }
31
32     Cow::speak;
33     Horse::speak;
34     Sheep::speak;
35
36 This results in:
37
38     a Cow goes moooo!
39     a Horse goes neigh!
40     a Sheep goes baaaah!
41
42 Nothing spectacular here.  Simple subroutines, albeit from separate
43 packages, and called using the full package name.  So let's create
44 an entire pasture:
45
46     # Cow::speak, Horse::speak, Sheep::speak as before
47     @pasture = qw(Cow Cow Horse Sheep Sheep);
48     foreach $animal (@pasture) {
49       &{$animal."::speak"};
50     }
51
52 This results in:
53
54     a Cow goes moooo!
55     a Cow goes moooo!
56     a Horse goes neigh!
57     a Sheep goes baaaah!
58     a Sheep goes baaaah!
59
60 Wow.  That symbolic coderef de-referencing there is pretty nasty.
61 We're counting on C<no strict refs> mode, certainly not recommended
62 for larger programs.  And why was that necessary?  Because the name of
63 the package seems to be inseparable from the name of the subroutine we
64 want to invoke within that package.
65
66 Or is it?
67
68 =head2 Introducing the method invocation arrow
69
70 For now, let's say that C<< Class->method >> invokes subroutine
71 C<method> in package C<Class>.  (Here, "Class" is used in its
72 "category" meaning, not its "scholastic" meaning.) That's not
73 completely accurate, but we'll do this one step at a time.  Now let's
74 use it like so:
75
76     # Cow::speak, Horse::speak, Sheep::speak as before
77     Cow->speak;
78     Horse->speak;
79     Sheep->speak;
80
81 And once again, this results in:
82
83     a Cow goes moooo!
84     a Horse goes neigh!
85     a Sheep goes baaaah!
86
87 That's not fun yet.  Same number of characters, all constant, no
88 variables.  But yet, the parts are separable now.  Watch:
89
90     $a = "Cow";
91     $a->speak; # invokes Cow->speak
92
93 Ahh!  Now that the package name has been parted from the subroutine
94 name, we can use a variable package name.  And this time, we've got
95 something that works even when C<use strict refs> is enabled.
96
97 =head2 Invoking a barnyard
98
99 Let's take that new arrow invocation and put it back in the barnyard
100 example:
101
102     sub Cow::speak {
103       print "a Cow goes moooo!\n";
104     }
105     sub Horse::speak {
106       print "a Horse goes neigh!\n";
107     }
108     sub Sheep::speak {
109       print "a Sheep goes baaaah!\n";
110     }
111
112     @pasture = qw(Cow Cow Horse Sheep Sheep);
113     foreach $animal (@pasture) {
114       $animal->speak;
115     }
116
117 There!  Now we have the animals all talking, and safely at that,
118 without the use of symbolic coderefs.
119
120 But look at all that common code.  Each of the C<speak> routines has a
121 similar structure: a C<print> operator and a string that contains
122 common text, except for two of the words.  It'd be nice if we could
123 factor out the commonality, in case we decide later to change it all
124 to C<says> instead of C<goes>.
125
126 And we actually have a way of doing that without much fuss, but we
127 have to hear a bit more about what the method invocation arrow is
128 actually doing for us.
129
130 =head2 The extra parameter of method invocation
131
132 The invocation of:
133
134     Class->method(@args)
135
136 attempts to invoke subroutine C<Class::method> as:
137
138     Class::method("Class", @args);
139
140 (If the subroutine can't be found, "inheritance" kicks in, but we'll
141 get to that later.)  This means that we get the class name as the
142 first parameter (the only parameter, if no arguments are given).  So
143 we can rewrite the C<Sheep> speaking subroutine as:
144
145     sub Sheep::speak {
146       my $class = shift;
147       print "a $class goes baaaah!\n";
148     }
149
150 And the other two animals come out similarly:
151
152     sub Cow::speak {
153       my $class = shift;
154       print "a $class goes moooo!\n";
155     }
156     sub Horse::speak {
157       my $class = shift;
158       print "a $class goes neigh!\n";
159     }
160
161 In each case, C<$class> will get the value appropriate for that
162 subroutine.  But once again, we have a lot of similar structure.  Can
163 we factor that out even further?  Yes, by calling another method in
164 the same class.
165
166 =head2 Calling a second method to simplify things
167
168 Let's call out from C<speak> to a helper method called C<sound>.
169 This method provides the constant text for the sound itself.
170
171     { package Cow;
172       sub sound { "moooo" }
173       sub speak {
174         my $class = shift;
175         print "a $class goes ", $class->sound, "!\n";
176       }
177     }
178
179 Now, when we call C<< Cow->speak >>, we get a C<$class> of C<Cow> in
180 C<speak>.  This in turn selects the C<< Cow->sound >> method, which
181 returns C<moooo>.  But how different would this be for the C<Horse>?
182
183     { package Horse;
184       sub sound { "neigh" }
185       sub speak {
186         my $class = shift;
187         print "a $class goes ", $class->sound, "!\n";
188       }
189     }
190
191 Only the name of the package and the specific sound change.  So can we
192 somehow share the definition for C<speak> between the Cow and the
193 Horse?  Yes, with inheritance!
194
195 =head2 Inheriting the windpipes
196
197 We'll define a common subroutine package called C<Animal>, with the
198 definition for C<speak>:
199
200     { package Animal;
201       sub speak {
202       my $class = shift;
203       print "a $class goes ", $class->sound, "!\n";
204       }
205     }
206
207 Then, for each animal, we say it "inherits" from C<Animal>, along
208 with the animal-specific sound:
209
210     { package Cow;
211       @ISA = qw(Animal);
212       sub sound { "moooo" }
213     }
214
215 Note the added C<@ISA> array (pronounced "is a").  We'll get to that in a minute.
216
217 But what happens when we invoke C<< Cow->speak >> now?
218
219 First, Perl constructs the argument list.  In this case, it's just
220 C<Cow>.  Then Perl looks for C<Cow::speak>.  But that's not there, so
221 Perl checks for the inheritance array C<@Cow::ISA>.  It's there,
222 and contains the single name C<Animal>.
223
224 Perl next checks for C<speak> inside C<Animal> instead, as in
225 C<Animal::speak>.  And that's found, so Perl invokes that subroutine
226 with the already frozen argument list.
227
228 Inside the C<Animal::speak> subroutine, C<$class> becomes C<Cow> (the
229 first argument).  So when we get to the step of invoking
230 C<< $class->sound >>, it'll be looking for C<< Cow->sound >>, which
231 gets it on the first try without looking at C<@ISA>.  Success!
232
233 =head2 A few notes about @ISA
234
235 This magical C<@ISA> variable has declared that C<Cow> "is a" C<Animal>.
236 Note that it's an array, not a simple single value, because on rare
237 occasions, it makes sense to have more than one parent class searched
238 for the missing methods.
239
240 If C<Animal> also had an C<@ISA>, then we'd check there too.  The
241 search is recursive, depth-first, left-to-right in each C<@ISA> by
242 default (see L<mro> for alternatives).  Typically, each C<@ISA> has
243 only one element (multiple elements means multiple inheritance and
244 multiple headaches), so we get a nice tree of inheritance.
245
246 When we turn on C<use strict>, we'll get complaints on C<@ISA>, since
247 it's not a variable containing an explicit package name, nor is it a
248 lexical ("my") variable.  We can't make it a lexical variable though
249 (it has to belong to the package to be found by the inheritance mechanism),
250 so there's a couple of straightforward ways to handle that.
251
252 The easiest is to just spell the package name out:
253
254     @Cow::ISA = qw(Animal);
255
256 Or declare it as package global variable:
257
258     package Cow;
259     our @ISA = qw(Animal);
260
261 Or allow it as an implicitly named package variable:
262
263     package Cow;
264     use vars qw(@ISA);
265     @ISA = qw(Animal);
266
267 If the C<Animal> class comes from another (object-oriented) module, then
268 just employ C<use base> to specify that C<Animal> should serve as the basis
269 for the C<Cow> class:
270
271     package Cow;
272     use base qw(Animal);
273
274 Now that's pretty darn simple!
275
276 =head2 Overriding the methods
277
278 Let's add a mouse, which can barely be heard:
279
280     # Animal package from before
281     { package Mouse;
282       @ISA = qw(Animal);
283       sub sound { "squeak" }
284       sub speak {
285         my $class = shift;
286         print "a $class goes ", $class->sound, "!\n";
287         print "[but you can barely hear it!]\n";
288       }
289     }
290
291     Mouse->speak;
292
293 which results in:
294
295     a Mouse goes squeak!
296     [but you can barely hear it!]
297
298 Here, C<Mouse> has its own speaking routine, so C<< Mouse->speak >>
299 doesn't immediately invoke C<< Animal->speak >>. This is known as
300 "overriding". In fact, we don't even need to say that a C<Mouse> is
301 an C<Animal> at all, because all of the methods needed for C<speak> are
302 completely defined for C<Mouse>; this is known as "duck typing":
303 "If it walks like a duck and quacks like a duck, I would call it a duck"
304 (James Whitcomb). However, it would probably be beneficial to allow a
305 closer examination to conclude that a C<Mouse> is indeed an C<Animal>,
306 so it is actually better to define C<Mouse> with C<Animal> as its base
307 (that is, it is better to "derive C<Mouse> from C<Animal>").
308
309 Moreover, this duplication of code could become a maintenance headache
310 (though code-reuse is not actually a good reason for inheritance; good
311 design practices dictate that a derived class should be usable wherever
312 its base class is usable, which might not be the outcome if code-reuse
313 is the sole criterion for inheritance. Just remember that a C<Mouse>
314 should always act like an C<Animal>).
315
316 So, let's make C<Mouse> an C<Animal>!
317
318 The obvious solution is to invoke C<Animal::speak> directly:
319
320     # Animal package from before
321     { package Mouse;
322       @ISA = qw(Animal);
323       sub sound { "squeak" }
324       sub speak {
325         my $class = shift;
326         Animal::speak($class);
327         print "[but you can barely hear it!]\n";
328       }
329     }
330
331 Note that we're using C<Animal::speak>. If we were to invoke
332 C<< Animal->speak >> instead, the first parameter to C<Animal::speak>
333 would automatically be C<"Animal"> rather than C<"Mouse">, so that
334 the call to C<< $class->sound >> in C<Animal::speak> would become
335 C<< Animal->sound >> rather than C<< Mouse->sound >>.
336
337 Also, without the method arrow C<< -> >>, it becomes necessary to specify
338 the first parameter to C<Animal::speak> ourselves, which is why C<$class>
339 is explicitly passed: C<Animal::speak($class)>.
340
341 However, invoking C<Animal::speak> directly is a mess: Firstly, it assumes
342 that the C<speak> method is a member of the C<Animal> class; what if C<Animal>
343 actually inherits C<speak> from its own base? Because we are no longer using
344 C<< -> >> to access C<speak>, the special method look up mechanism wouldn't be
345 used, so C<speak> wouldn't even be found!
346
347 The second problem is more subtle: C<Animal> is now hardwired into the subroutine
348 selection. Let's assume that C<Animal::speak> does exist. What happens when,
349 at a later time, someone expands the class hierarchy by having C<Mouse>
350 inherit from C<Mus> instead of C<Animal>. Unless the invocation of C<Animal::speak>
351 is also changed to an invocation of C<Mus::speak>, centuries worth of taxonomical
352 classification could be obliterated!
353
354 What we have here is a fragile or leaky abstraction; it is the beginning of a
355 maintenance nightmare. What we need is the ability to search for the right
356 method wih as few assumptions as possible.
357
358 =head2 Starting the search from a different place
359
360 A I<better> solution is to tell Perl where in the inheritance chain to begin searching
361 for C<speak>. This can be achieved with a modified version of the method arrow C<< -> >>:
362
363     ClassName->FirstPlaceToLook::method
364
365 So, the improved C<Mouse> class is:
366
367     # same Animal as before
368     { package Mouse;
369       # same @ISA, &sound as before
370       sub speak {
371         my $class = shift;
372         $class->Animal::speak;
373         print "[but you can barely hear it!]\n";
374       }
375     }
376
377 Using this syntax, we start with C<Animal> to find C<speak>, and then
378 use all of C<Animal>'s inheritance chain if it is not found immediately.
379 As usual, the first parameter to C<speak> would be C<$class>, so we no
380 longer need to pass C<$class> explicitly to C<speak>.
381
382 But what about the second problem? We're still hardwiring C<Animal> into
383 the method lookup.
384
385 =head2 The SUPER way of doing things
386
387 If C<Animal> is replaced with the special placeholder C<SUPER> in that
388 invocation, then the contents of C<Mouse>'s C<@ISA> are used for the
389 search, beginning with C<$ISA[0]>. So, all of the problems can be fixed
390 as follows:
391
392     # same Animal as before
393     { package Mouse;
394       # same @ISA, &sound as before
395       sub speak {
396         my $class = shift;
397         $class->SUPER::speak;
398         print "[but you can barely hear it!]\n";
399       }
400     }
401
402 In general, C<SUPER::speak> means look in the current package's C<@ISA>
403 for a class that implements C<speak>, and invoke the first one found.
404 The placeholder is called C<SUPER>, because many other languages refer
405 to base classes as "I<super>classes", and Perl likes to be eclectic.
406
407 Note that a call such as
408
409     $class->SUPER::method;
410
411 does I<not> look in the C<@ISA> of C<$class> unless C<$class> happens to
412 be the current package.
413
414 =head2 Where we're at so far...
415
416 So far, we've seen the method arrow syntax:
417
418   Class->method(@args);
419
420 or the equivalent:
421
422   $a = "Class";
423   $a->method(@args);
424
425 which constructs an argument list of:
426
427   ("Class", @args)
428
429 and attempts to invoke
430
431   Class::method("Class", @Args);
432
433 However, if C<Class::method> is not found, then C<@Class::ISA> is examined
434 (recursively) to locate a package that does indeed contain C<method>,
435 and that subroutine is invoked instead.
436
437 Using this simple syntax, we have class methods, (multiple)
438 inheritance, overriding, and extending.  Using just what we've seen so
439 far, we've been able to factor out common code, and provide a nice way
440 to reuse implementations with variations.  This is at the core of what
441 objects provide, but objects also provide instance data, which we
442 haven't even begun to cover.
443
444 =head2 A horse is a horse, of course of course -- or is it?
445
446 Let's start with the code for the C<Animal> class
447 and the C<Horse> class:
448
449   { package Animal;
450     sub speak {
451       my $class = shift;
452       print "a $class goes ", $class->sound, "!\n";
453     }
454   }
455   { package Horse;
456     @ISA = qw(Animal);
457     sub sound { "neigh" }
458   }
459
460 This lets us invoke C<< Horse->speak >> to ripple upward to
461 C<Animal::speak>, calling back to C<Horse::sound> to get the specific
462 sound, and the output of:
463
464   a Horse goes neigh!
465
466 But all of our Horse objects would have to be absolutely identical.
467 If I add a subroutine, all horses automatically share it.  That's
468 great for making horses the same, but how do we capture the
469 distinctions about an individual horse?  For example, suppose I want
470 to give my first horse a name.  There's got to be a way to keep its
471 name separate from the other horses.
472
473 We can do that by drawing a new distinction, called an "instance".
474 An "instance" is generally created by a class.  In Perl, any reference
475 can be an instance, so let's start with the simplest reference
476 that can hold a horse's name: a scalar reference.
477
478   my $name = "Mr. Ed";
479   my $talking = \$name;
480
481 So now C<$talking> is a reference to what will be the instance-specific
482 data (the name).  The final step in turning this into a real instance
483 is with a special operator called C<bless>:
484
485   bless $talking, Horse;
486
487 This operator stores information about the package named C<Horse> into
488 the thing pointed at by the reference.  At this point, we say
489 C<$talking> is an instance of C<Horse>.  That is, it's a specific
490 horse.  The reference is otherwise unchanged, and can still be used
491 with traditional dereferencing operators.
492
493 =head2 Invoking an instance method
494
495 The method arrow can be used on instances, as well as names of
496 packages (classes).  So, let's get the sound that C<$talking> makes:
497
498   my $noise = $talking->sound;
499
500 To invoke C<sound>, Perl first notes that C<$talking> is a blessed
501 reference (and thus an instance).  It then constructs an argument
502 list, in this case from just C<($talking)>.  (Later we'll see that
503 arguments will take their place following the instance variable,
504 just like with classes.)
505
506 Now for the fun part: Perl takes the class in which the instance was
507 blessed, in this case C<Horse>, and uses that to locate the subroutine
508 to invoke the method.  In this case, C<Horse::sound> is found directly
509 (without using inheritance), yielding the final subroutine invocation:
510
511   Horse::sound($talking)
512
513 Note that the first parameter here is still the instance, not the name
514 of the class as before.  We'll get C<neigh> as the return value, and
515 that'll end up as the C<$noise> variable above.
516
517 If Horse::sound had not been found, we'd be wandering up the
518 C<@Horse::ISA> list to try to find the method in one of the
519 superclasses, just as for a class method.  The only difference between
520 a class method and an instance method is whether the first parameter
521 is an instance (a blessed reference) or a class name (a string).
522
523 =head2 Accessing the instance data
524
525 Because we get the instance as the first parameter, we can now access
526 the instance-specific data.  In this case, let's add a way to get at
527 the name:
528
529   { package Horse;
530     @ISA = qw(Animal);
531     sub sound { "neigh" }
532     sub name {
533       my $self = shift;
534       $$self;
535     }
536   }
537
538 Now we call for the name:
539
540   print $talking->name, " says ", $talking->sound, "\n";
541
542 Inside C<Horse::name>, the C<@_> array contains just C<$talking>,
543 which the C<shift> stores into C<$self>.  (It's traditional to shift
544 the first parameter off into a variable named C<$self> for instance
545 methods, so stay with that unless you have strong reasons otherwise.)
546 Then, C<$self> gets de-referenced as a scalar ref, yielding C<Mr. Ed>,
547 and we're done with that.  The result is:
548
549   Mr. Ed says neigh.
550
551 =head2 How to build a horse
552
553 Of course, if we constructed all of our horses by hand, we'd most
554 likely make mistakes from time to time.  We're also violating one of
555 the properties of object-oriented programming, in that the "inside
556 guts" of a Horse are visible.  That's good if you're a veterinarian,
557 but not if you just like to own horses.  So, let's let the Horse class
558 build a new horse:
559
560   { package Horse;
561     @ISA = qw(Animal);
562     sub sound { "neigh" }
563     sub name {
564       my $self = shift;
565       $$self;
566     }
567     sub named {
568       my $class = shift;
569       my $name = shift;
570       bless \$name, $class;
571     }
572   }
573
574 Now with the new C<named> method, we can build a horse:
575
576   my $talking = Horse->named("Mr. Ed");
577
578 Notice we're back to a class method, so the two arguments to
579 C<Horse::named> are C<Horse> and C<Mr. Ed>.  The C<bless> operator
580 not only blesses C<$name>, it also returns the reference to C<$name>,
581 so that's fine as a return value.  And that's how to build a horse.
582
583 We've called the constructor C<named> here, so that it quickly denotes
584 the constructor's argument as the name for this particular C<Horse>.
585 You can use different constructors with different names for different
586 ways of "giving birth" to the object (like maybe recording its
587 pedigree or date of birth).  However, you'll find that most people
588 coming to Perl from more limited languages use a single constructor
589 named C<new>, with various ways of interpreting the arguments to
590 C<new>.  Either style is fine, as long as you document your particular
591 way of giving birth to an object.  (And you I<were> going to do that,
592 right?)
593
594 =head2 Inheriting the constructor
595
596 But was there anything specific to C<Horse> in that method?  No.  Therefore,
597 it's also the same recipe for building anything else that inherited from
598 C<Animal>, so let's put it there:
599
600   { package Animal;
601     sub speak {
602       my $class = shift;
603       print "a $class goes ", $class->sound, "!\n";
604     }
605     sub name {
606       my $self = shift;
607       $$self;
608     }
609     sub named {
610       my $class = shift;
611       my $name = shift;
612       bless \$name, $class;
613     }
614   }
615   { package Horse;
616     @ISA = qw(Animal);
617     sub sound { "neigh" }
618   }
619
620 Ahh, but what happens if we invoke C<speak> on an instance?
621
622   my $talking = Horse->named("Mr. Ed");
623   $talking->speak;
624
625 We get a debugging value:
626
627   a Horse=SCALAR(0xaca42ac) goes neigh!
628
629 Why?  Because the C<Animal::speak> routine is expecting a classname as
630 its first parameter, not an instance.  When the instance is passed in,
631 we'll end up using a blessed scalar reference as a string, and that
632 shows up as we saw it just now.
633
634 =head2 Making a method work with either classes or instances
635
636 All we need is for a method to detect if it is being called on a class
637 or called on an instance.  The most straightforward way is with the
638 C<ref> operator.  This returns a string (the classname) when used on a
639 blessed reference, and an empty string when used on a string (like a
640 classname).  Let's modify the C<name> method first to notice the change:
641
642   sub name {
643     my $either = shift;
644     ref $either
645       ? $$either # it's an instance, return name
646       : "an unnamed $either"; # it's a class, return generic
647   }
648
649 Here, the C<?:> operator comes in handy to select either the
650 dereference or a derived string.  Now we can use this with either an
651 instance or a class.  Note that I've changed the first parameter
652 holder to C<$either> to show that this is intended:
653
654   my $talking = Horse->named("Mr. Ed");
655   print Horse->name, "\n"; # prints "an unnamed Horse\n"
656   print $talking->name, "\n"; # prints "Mr Ed.\n"
657
658 and now we'll fix C<speak> to use this:
659
660   sub speak {
661     my $either = shift;
662     print $either->name, " goes ", $either->sound, "\n";
663   }
664
665 And since C<sound> already worked with either a class or an instance,
666 we're done!
667
668 =head2 Adding parameters to a method
669
670 Let's train our animals to eat:
671
672   { package Animal;
673     sub named {
674       my $class = shift;
675       my $name = shift;
676       bless \$name, $class;
677     }
678     sub name {
679       my $either = shift;
680       ref $either
681         ? $$either # it's an instance, return name
682         : "an unnamed $either"; # it's a class, return generic
683     }
684     sub speak {
685       my $either = shift;
686       print $either->name, " goes ", $either->sound, "\n";
687     }
688     sub eat {
689       my $either = shift;
690       my $food = shift;
691       print $either->name, " eats $food.\n";
692     }
693   }
694   { package Horse;
695     @ISA = qw(Animal);
696     sub sound { "neigh" }
697   }
698   { package Sheep;
699     @ISA = qw(Animal);
700     sub sound { "baaaah" }
701   }
702
703 And now try it out:
704
705   my $talking = Horse->named("Mr. Ed");
706   $talking->eat("hay");
707   Sheep->eat("grass");
708
709 which prints:
710
711   Mr. Ed eats hay.
712   an unnamed Sheep eats grass.
713
714 An instance method with parameters gets invoked with the instance,
715 and then the list of parameters.  So that first invocation is like:
716
717   Animal::eat($talking, "hay");
718
719 =head2 More interesting instances
720
721 What if an instance needs more data?  Most interesting instances are
722 made of many items, each of which can in turn be a reference or even
723 another object.  The easiest way to store these is often in a hash.
724 The keys of the hash serve as the names of parts of the object (often
725 called "instance variables" or "member variables"), and the
726 corresponding values are, well, the values.
727
728 But how do we turn the horse into a hash?  Recall that an object was
729 any blessed reference.  We can just as easily make it a blessed hash
730 reference as a blessed scalar reference, as long as everything that
731 looks at the reference is changed accordingly.
732
733 Let's make a sheep that has a name and a color:
734
735   my $bad = bless { Name => "Evil", Color => "black" }, Sheep;
736
737 so C<< $bad->{Name} >> has C<Evil>, and C<< $bad->{Color} >> has
738 C<black>.  But we want to make C<< $bad->name >> access the name, and
739 that's now messed up because it's expecting a scalar reference.  Not
740 to worry, because that's pretty easy to fix up:
741
742   ## in Animal
743   sub name {
744     my $either = shift;
745     ref $either ?
746       $either->{Name} :
747       "an unnamed $either";
748   }
749
750 And of course C<named> still builds a scalar sheep, so let's fix that
751 as well:
752
753   ## in Animal
754   sub named {
755     my $class = shift;
756     my $name = shift;
757     my $self = { Name => $name, Color => $class->default_color };
758     bless $self, $class;
759   }
760
761 What's this C<default_color>?  Well, if C<named> has only the name,
762 we still need to set a color, so we'll have a class-specific initial color.
763 For a sheep, we might define it as white:
764
765   ## in Sheep
766   sub default_color { "white" }
767
768 And then to keep from having to define one for each additional class,
769 we'll define a "backstop" method that serves as the "default default",
770 directly in C<Animal>:
771
772   ## in Animal
773   sub default_color { "brown" }
774
775 Now, because C<name> and C<named> were the only methods that
776 referenced the "structure" of the object, the rest of the methods can
777 remain the same, so C<speak> still works as before.
778
779 =head2 A horse of a different color
780
781 But having all our horses be brown would be boring.  So let's add a
782 method or two to get and set the color.
783
784   ## in Animal
785   sub color {
786     $_[0]->{Color}
787   }
788   sub set_color {
789     $_[0]->{Color} = $_[1];
790   }
791
792 Note the alternate way of accessing the arguments: C<$_[0]> is used
793 in-place, rather than with a C<shift>.  (This saves us a bit of time
794 for something that may be invoked frequently.)  And now we can fix
795 that color for Mr. Ed:
796
797   my $talking = Horse->named("Mr. Ed");
798   $talking->set_color("black-and-white");
799   print $talking->name, " is colored ", $talking->color, "\n";
800
801 which results in:
802
803   Mr. Ed is colored black-and-white
804
805 =head2 Summary
806
807 So, now we have class methods, constructors, instance methods,
808 instance data, and even accessors.  But that's still just the
809 beginning of what Perl has to offer.  We haven't even begun to talk
810 about accessors that double as getters and setters, destructors,
811 indirect object notation, subclasses that add instance data, per-class
812 data, overloading, "isa" and "can" tests, C<UNIVERSAL> class, and so
813 on.  That's for the rest of the Perl documentation to cover.
814 Hopefully, this gets you started, though.
815
816 =head1 SEE ALSO
817
818 For more information, see L<perlobj> (for all the gritty details about
819 Perl objects, now that you've seen the basics), L<perltoot> (the
820 tutorial for those who already know objects), L<perltooc> (dealing
821 with class data), L<perlbot> (for some more tricks), and books such as
822 Damian Conway's excellent I<Object Oriented Perl>.
823
824 Some modules which might prove interesting are Class::Accessor,
825 Class::Class, Class::Contract, Class::Data::Inheritable,
826 Class::MethodMaker and Tie::SecureHash
827
828 =head1 COPYRIGHT
829
830 Copyright (c) 1999, 2000 by Randal L. Schwartz and Stonehenge
831 Consulting Services, Inc.  Permission is hereby granted to distribute
832 this document intact with the Perl distribution, and in accordance
833 with the licenses of the Perl distribution; derived documents must
834 include this copyright notice intact.
835
836 Portions of this text have been derived from Perl Training materials
837 originally appearing in the I<Packages, References, Objects, and
838 Modules> course taught by instructors for Stonehenge Consulting
839 Services, Inc. and used with permission.
840
841 Portions of this text have been derived from materials originally
842 appearing in I<Linux Magazine> and used with permission.