Integrate perlio:
[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 {
29 print "a Sheep goes baaaah!\n"
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 {
109 print "a Sheep goes baaaah!\n"
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;
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;
187 print "a $class goes ", $class->sound, "!\n"
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;
203 print "a $class goes ", $class->sound, "!\n"
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
241search is recursive, depth-first, left-to-right in each C<@ISA>.
242Typically, each C<@ISA> has only one element (multiple elements means
243multiple inheritance and multiple headaches), so we get a nice tree of
244inheritance.
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
dbe48302 256Or allow it as an implicitly named package variable:
694468e3 257
258 package Cow;
84f709e7 259 use vars qw(@ISA);
260 @ISA = qw(Animal);
694468e3 261
262If you're bringing in the class from outside, via an object-oriented
263module, you change:
264
265 package Cow;
266 use Animal;
84f709e7 267 use vars qw(@ISA);
268 @ISA = qw(Animal);
694468e3 269
270into just:
271
272 package Cow;
273 use base qw(Animal);
274
84f709e7 275And that's pretty darn compact.
694468e3 276
277=head2 Overriding the methods
278
279Let's add a mouse, which can barely be heard:
280
84f709e7 281 # Animal package from before
282 { package Mouse;
283 @ISA = qw(Animal);
694468e3 284 sub sound { "squeak" }
285 sub speak {
286 my $class = shift;
287 print "a $class goes ", $class->sound, "!\n";
288 print "[but you can barely hear it!]\n";
289 }
290 }
291
292 Mouse->speak;
293
294which results in:
295
296 a Mouse goes squeak!
297 [but you can barely hear it!]
298
c47ff5f1 299Here, C<Mouse> has its own speaking routine, so C<< Mouse->speak >>
300doesn't immediately invoke C<< Animal->speak >>. This is known as
694468e3 301"overriding". In fact, we didn't even need to say that a C<Mouse> was
302an C<Animal> at all, since all of the methods needed for C<speak> are
303completely defined with C<Mouse>.
304
c47ff5f1 305But we've now duplicated some of the code from C<< Animal->speak >>,
694468e3 306and this can once again be a maintenance headache. So, can we avoid
307that? Can we say somehow that a C<Mouse> does everything any other
308C<Animal> does, but add in the extra comment? Sure!
309
310First, we can invoke the C<Animal::speak> method directly:
311
84f709e7 312 # Animal package from before
313 { package Mouse;
314 @ISA = qw(Animal);
694468e3 315 sub sound { "squeak" }
316 sub speak {
317 my $class = shift;
318 Animal::speak($class);
319 print "[but you can barely hear it!]\n";
320 }
321 }
322
323Note that we have to include the C<$class> parameter (almost surely
324the value of C<"Mouse">) as the first parameter to C<Animal::speak>,
325since we've stopped using the method arrow. Why did we stop? Well,
c47ff5f1 326if we invoke C<< Animal->speak >> there, the first parameter to the
694468e3 327method will be C<"Animal"> not C<"Mouse">, and when time comes for it
328to call for the C<sound>, it won't have the right class to come back
329to this package.
330
331Invoking C<Animal::speak> directly is a mess, however. What if
332C<Animal::speak> didn't exist before, and was being inherited from a
333class mentioned in C<@Animal::ISA>? Because we are no longer using
334the method arrow, we get one and only one chance to hit the right
335subroutine.
336
337Also note that the C<Animal> classname is now hardwired into the
338subroutine selection. This is a mess if someone maintains the code,
339changing C<@ISA> for <Mouse> and didn't notice C<Animal> there in
340C<speak>. So, this is probably not the right way to go.
341
342=head2 Starting the search from a different place
343
344A better solution is to tell Perl to search from a higher place
345in the inheritance chain:
346
347 # same Animal as before
84f709e7 348 { package Mouse;
694468e3 349 # same @ISA, &sound as before
350 sub speak {
351 my $class = shift;
352 $class->Animal::speak;
353 print "[but you can barely hear it!]\n";
354 }
355 }
356
357Ahh. This works. Using this syntax, we start with C<Animal> to find
358C<speak>, and use all of C<Animal>'s inheritance chain if not found
359immediately. And yet the first parameter will be C<$class>, so the
360found C<speak> method will get C<Mouse> as its first entry, and
361eventually work its way back to C<Mouse::sound> for the details.
362
363But this isn't the best solution. We still have to keep the C<@ISA>
364and the initial search package coordinated. Worse, if C<Mouse> had
365multiple entries in C<@ISA>, we wouldn't necessarily know which one
366had actually defined C<speak>. So, is there an even better way?
367
368=head2 The SUPER way of doing things
369
370By changing the C<Animal> class to the C<SUPER> class in that
371invocation, we get a search of all of our super classes (classes
372listed in C<@ISA>) automatically:
373
374 # same Animal as before
84f709e7 375 { package Mouse;
694468e3 376 # same @ISA, &sound as before
377 sub speak {
378 my $class = shift;
379 $class->SUPER::speak;
380 print "[but you can barely hear it!]\n";
381 }
382 }
383
384So, C<SUPER::speak> means look in the current package's C<@ISA> for
385C<speak>, invoking the first one found.
386
387=head2 Where we're at so far...
388
389So far, we've seen the method arrow syntax:
390
391 Class->method(@args);
392
393or the equivalent:
394
84f709e7 395 $a = "Class";
694468e3 396 $a->method(@args);
397
398which constructs an argument list of:
399
400 ("Class", @args)
401
402and attempts to invoke
403
404 Class::method("Class", @Args);
405
406However, if C<Class::method> is not found, then C<@Class::ISA> is examined
407(recursively) to locate a package that does indeed contain C<method>,
408and that subroutine is invoked instead.
409
410Using this simple syntax, we have class methods, (multiple)
411inheritance, overriding, and extending. Using just what we've seen so
412far, we've been able to factor out common code, and provide a nice way
413to reuse implementations with variations. This is at the core of what
414objects provide, but objects also provide instance data, which we
415haven't even begun to cover.
416
417=head2 A horse is a horse, of course of course -- or is it?
418
419Let's start with the code for the C<Animal> class
420and the C<Horse> class:
421
84f709e7 422 { package Animal;
694468e3 423 sub speak {
424 my $class = shift;
425 print "a $class goes ", $class->sound, "!\n"
426 }
427 }
84f709e7 428 { package Horse;
429 @ISA = qw(Animal);
694468e3 430 sub sound { "neigh" }
431 }
432
c47ff5f1 433This lets us invoke C<< Horse->speak >> to ripple upward to
694468e3 434C<Animal::speak>, calling back to C<Horse::sound> to get the specific
435sound, and the output of:
436
437 a Horse goes neigh!
438
439But all of our Horse objects would have to be absolutely identical.
440If I add a subroutine, all horses automatically share it. That's
441great for making horses the same, but how do we capture the
442distinctions about an individual horse? For example, suppose I want
443to give my first horse a name. There's got to be a way to keep its
444name separate from the other horses.
445
446We can do that by drawing a new distinction, called an "instance".
447An "instance" is generally created by a class. In Perl, any reference
448can be an instance, so let's start with the simplest reference
449that can hold a horse's name: a scalar reference.
450
84f709e7 451 my $name = "Mr. Ed";
694468e3 452 my $talking = \$name;
453
454So now C<$talking> is a reference to what will be the instance-specific
455data (the name). The final step in turning this into a real instance
456is with a special operator called C<bless>:
457
458 bless $talking, Horse;
459
460This operator stores information about the package named C<Horse> into
461the thing pointed at by the reference. At this point, we say
462C<$talking> is an instance of C<Horse>. That is, it's a specific
463horse. The reference is otherwise unchanged, and can still be used
464with traditional dereferencing operators.
465
466=head2 Invoking an instance method
467
468The method arrow can be used on instances, as well as names of
469packages (classes). So, let's get the sound that C<$talking> makes:
470
471 my $noise = $talking->sound;
472
473To invoke C<sound>, Perl first notes that C<$talking> is a blessed
474reference (and thus an instance). It then constructs an argument
475list, in this case from just C<($talking)>. (Later we'll see that
476arguments will take their place following the instance variable,
477just like with classes.)
478
479Now for the fun part: Perl takes the class in which the instance was
480blessed, in this case C<Horse>, and uses that to locate the subroutine
481to invoke the method. In this case, C<Horse::sound> is found directly
482(without using inheritance), yielding the final subroutine invocation:
483
484 Horse::sound($talking)
485
486Note that the first parameter here is still the instance, not the name
487of the class as before. We'll get C<neigh> as the return value, and
488that'll end up as the C<$noise> variable above.
489
490If Horse::sound had not been found, we'd be wandering up the
491C<@Horse::ISA> list to try to find the method in one of the
492superclasses, just as for a class method. The only difference between
493a class method and an instance method is whether the first parameter
dbe48302 494is an instance (a blessed reference) or a class name (a string).
694468e3 495
496=head2 Accessing the instance data
497
498Because we get the instance as the first parameter, we can now access
499the instance-specific data. In this case, let's add a way to get at
500the name:
501
84f709e7 502 { package Horse;
503 @ISA = qw(Animal);
694468e3 504 sub sound { "neigh" }
505 sub name {
506 my $self = shift;
507 $$self;
508 }
509 }
c47ff5f1 510
694468e3 511Now we call for the name:
512
513 print $talking->name, " says ", $talking->sound, "\n";
514
515Inside C<Horse::name>, the C<@_> array contains just C<$talking>,
516which the C<shift> stores into C<$self>. (It's traditional to shift
517the first parameter off into a variable named C<$self> for instance
518methods, so stay with that unless you have strong reasons otherwise.)
519Then, C<$self> gets de-referenced as a scalar ref, yielding C<Mr. Ed>,
520and we're done with that. The result is:
521
522 Mr. Ed says neigh.
523
524=head2 How to build a horse
525
526Of course, if we constructed all of our horses by hand, we'd most
527likely make mistakes from time to time. We're also violating one of
528the properties of object-oriented programming, in that the "inside
529guts" of a Horse are visible. That's good if you're a veterinarian,
530but not if you just like to own horses. So, let's let the Horse class
531build a new horse:
532
84f709e7 533 { package Horse;
534 @ISA = qw(Animal);
694468e3 535 sub sound { "neigh" }
536 sub name {
537 my $self = shift;
538 $$self;
539 }
540 sub named {
541 my $class = shift;
84f709e7 542 my $name = shift;
694468e3 543 bless \$name, $class;
544 }
545 }
546
547Now with the new C<named> method, we can build a horse:
548
549 my $talking = Horse->named("Mr. Ed");
550
551Notice we're back to a class method, so the two arguments to
552C<Horse::named> are C<Horse> and C<Mr. Ed>. The C<bless> operator
553not only blesses C<$name>, it also returns the reference to C<$name>,
554so that's fine as a return value. And that's how to build a horse.
555
dbe48302 556We've called the constructor C<named> here, so that it quickly denotes
557the constructor's argument as the name for this particular C<Horse>.
558You can use different constructors with different names for different
559ways of "giving birth" to the object (like maybe recording its
560pedigree or date of birth). However, you'll find that most people
561coming to Perl from more limited languages use a single constructor
562named C<new>, with various ways of interpreting the arguments to
563C<new>. Either style is fine, as long as you document your particular
564way of giving birth to an object. (And you I<were> going to do that,
565right?)
566
694468e3 567=head2 Inheriting the constructor
568
569But was there anything specific to C<Horse> in that method? No. Therefore,
570it's also the same recipe for building anything else that inherited from
571C<Animal>, so let's put it there:
572
84f709e7 573 { package Animal;
694468e3 574 sub speak {
575 my $class = shift;
576 print "a $class goes ", $class->sound, "!\n"
577 }
578 sub name {
579 my $self = shift;
580 $$self;
581 }
582 sub named {
583 my $class = shift;
84f709e7 584 my $name = shift;
694468e3 585 bless \$name, $class;
586 }
587 }
84f709e7 588 { package Horse;
589 @ISA = qw(Animal);
694468e3 590 sub sound { "neigh" }
591 }
592
593Ahh, but what happens if we invoke C<speak> on an instance?
594
595 my $talking = Horse->named("Mr. Ed");
596 $talking->speak;
597
598We get a debugging value:
599
600 a Horse=SCALAR(0xaca42ac) goes neigh!
601
602Why? Because the C<Animal::speak> routine is expecting a classname as
603its first parameter, not an instance. When the instance is passed in,
604we'll end up using a blessed scalar reference as a string, and that
605shows up as we saw it just now.
606
607=head2 Making a method work with either classes or instances
608
609All we need is for a method to detect if it is being called on a class
610or called on an instance. The most straightforward way is with the
611C<ref> operator. This returns a string (the classname) when used on a
612blessed reference, and C<undef> when used on a string (like a
613classname). Let's modify the C<name> method first to notice the change:
614
615 sub name {
616 my $either = shift;
617 ref $either
84f709e7 618 ? $$either # it's an instance, return name
694468e3 619 : "an unnamed $either"; # it's a class, return generic
620 }
621
622Here, the C<?:> operator comes in handy to select either the
623dereference or a derived string. Now we can use this with either an
624instance or a class. Note that I've changed the first parameter
625holder to C<$either> to show that this is intended:
626
627 my $talking = Horse->named("Mr. Ed");
84f709e7 628 print Horse->name, "\n"; # prints "an unnamed Horse\n"
694468e3 629 print $talking->name, "\n"; # prints "Mr Ed.\n"
630
631and now we'll fix C<speak> to use this:
632
633 sub speak {
634 my $either = shift;
635 print $either->name, " goes ", $either->sound, "\n";
636 }
637
638And since C<sound> already worked with either a class or an instance,
639we're done!
640
641=head2 Adding parameters to a method
642
643Let's train our animals to eat:
644
84f709e7 645 { package Animal;
694468e3 646 sub named {
647 my $class = shift;
84f709e7 648 my $name = shift;
694468e3 649 bless \$name, $class;
650 }
651 sub name {
652 my $either = shift;
653 ref $either
84f709e7 654 ? $$either # it's an instance, return name
694468e3 655 : "an unnamed $either"; # it's a class, return generic
656 }
657 sub speak {
658 my $either = shift;
659 print $either->name, " goes ", $either->sound, "\n";
660 }
661 sub eat {
662 my $either = shift;
84f709e7 663 my $food = shift;
694468e3 664 print $either->name, " eats $food.\n";
665 }
666 }
84f709e7 667 { package Horse;
668 @ISA = qw(Animal);
694468e3 669 sub sound { "neigh" }
670 }
84f709e7 671 { package Sheep;
672 @ISA = qw(Animal);
694468e3 673 sub sound { "baaaah" }
674 }
675
676And now try it out:
677
678 my $talking = Horse->named("Mr. Ed");
679 $talking->eat("hay");
680 Sheep->eat("grass");
681
682which prints:
683
684 Mr. Ed eats hay.
685 an unnamed Sheep eats grass.
686
687An instance method with parameters gets invoked with the instance,
688and then the list of parameters. So that first invocation is like:
689
690 Animal::eat($talking, "hay");
691
692=head2 More interesting instances
693
694What if an instance needs more data? Most interesting instances are
695made of many items, each of which can in turn be a reference or even
696another object. The easiest way to store these is often in a hash.
697The keys of the hash serve as the names of parts of the object (often
698called "instance variables" or "member variables"), and the
699corresponding values are, well, the values.
700
701But how do we turn the horse into a hash? Recall that an object was
702any blessed reference. We can just as easily make it a blessed hash
703reference as a blessed scalar reference, as long as everything that
704looks at the reference is changed accordingly.
705
706Let's make a sheep that has a name and a color:
707
84f709e7 708 my $bad = bless { Name => "Evil", Color => "black" }, Sheep;
694468e3 709
c47ff5f1 710so C<< $bad->{Name} >> has C<Evil>, and C<< $bad->{Color} >> has
711C<black>. But we want to make C<< $bad->name >> access the name, and
694468e3 712that's now messed up because it's expecting a scalar reference. Not
713to worry, because that's pretty easy to fix up:
714
715 ## in Animal
716 sub name {
717 my $either = shift;
718 ref $either ?
719 $either->{Name} :
720 "an unnamed $either";
721 }
722
723And of course C<named> still builds a scalar sheep, so let's fix that
724as well:
725
726 ## in Animal
727 sub named {
728 my $class = shift;
84f709e7 729 my $name = shift;
730 my $self = { Name => $name, Color => $class->default_color };
694468e3 731 bless $self, $class;
732 }
733
734What's this C<default_color>? Well, if C<named> has only the name,
735we still need to set a color, so we'll have a class-specific initial color.
736For a sheep, we might define it as white:
737
738 ## in Sheep
739 sub default_color { "white" }
740
741And then to keep from having to define one for each additional class,
742we'll define a "backstop" method that serves as the "default default",
743directly in C<Animal>:
744
745 ## in Animal
746 sub default_color { "brown" }
747
748Now, because C<name> and C<named> were the only methods that
749referenced the "structure" of the object, the rest of the methods can
750remain the same, so C<speak> still works as before.
751
752=head2 A horse of a different color
753
754But having all our horses be brown would be boring. So let's add a
755method or two to get and set the color.
756
757 ## in Animal
758 sub color {
759 $_[0]->{Color}
760 }
761 sub set_color {
762 $_[0]->{Color} = $_[1];
763 }
764
765Note the alternate way of accessing the arguments: C<$_[0]> is used
766in-place, rather than with a C<shift>. (This saves us a bit of time
767for something that may be invoked frequently.) And now we can fix
768that color for Mr. Ed:
769
770 my $talking = Horse->named("Mr. Ed");
771 $talking->set_color("black-and-white");
772 print $talking->name, " is colored ", $talking->color, "\n";
773
774which results in:
775
776 Mr. Ed is colored black-and-white
777
778=head2 Summary
779
780So, now we have class methods, constructors, instance methods,
781instance data, and even accessors. But that's still just the
782beginning of what Perl has to offer. We haven't even begun to talk
783about accessors that double as getters and setters, destructors,
784indirect object notation, subclasses that add instance data, per-class
785data, overloading, "isa" and "can" tests, C<UNIVERSAL> class, and so
786on. That's for the rest of the Perl documentation to cover.
787Hopefully, this gets you started, though.
788
789=head1 SEE ALSO
790
791For more information, see L<perlobj> (for all the gritty details about
792Perl objects, now that you've seen the basics), L<perltoot> (the
890a53b9 793tutorial for those who already know objects), L<perltooc> (dealing
8257a158 794with class data), L<perlbot> (for some more tricks), and books such as
795Damian Conway's excellent I<Object Oriented Perl>.
796
797Some modules which might prove interesting are Class::Accessor,
798Class::Class, Class::Contract, Class::Data::Inheritable,
799Class::MethodMaker and Tie::SecureHash
694468e3 800
801=head1 COPYRIGHT
802
803Copyright (c) 1999, 2000 by Randal L. Schwartz and Stonehenge
804Consulting Services, Inc. Permission is hereby granted to distribute
805this document intact with the Perl distribution, and in accordance
806with the licenses of the Perl distribution; derived documents must
807include this copyright notice intact.
808
809Portions of this text have been derived from Perl Training materials
810originally appearing in the I<Packages, References, Objects, and
811Modules> course taught by instructors for Stonehenge Consulting
812Services, Inc. and used with permission.
813
814Portions of this text have been derived from materials originally
815appearing in I<Linux Magazine> and used with permission.