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