1PERLBOOT(1)            Perl Programmers Reference Guide            PERLBOOT(1)
2
3
4

NAME

6       perlboot - Beginner's Object-Oriented Tutorial
7

DESCRIPTION

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

SEE ALSO

836       For more information, see perlobj (for all the gritty details about
837       Perl objects, now that you've seen the basics), perltoot (the tutorial
838       for those who already know objects), perltooc (dealing with class
839       data), perlbot (for some more tricks), and books such as Damian
840       Conway's excellent Object Oriented Perl.
841
842       Some modules which might prove interesting are Class::Accessor,
843       Class::Class, Class::Contract, Class::Data::Inheritable,
844       Class::MethodMaker and Tie::SecureHash
845
847       Copyright (c) 1999, 2000 by Randal L. Schwartz and Stonehenge
848       Consulting Services, Inc.
849
850       Copyright (c) 2009 by Michael F. Witten.
851
852       Permission is hereby granted to distribute this document intact with
853       the Perl distribution, and in accordance with the licenses of the Perl
854       distribution; derived documents must include this copyright notice
855       intact.
856
857       Portions of this text have been derived from Perl Training materials
858       originally appearing in the Packages, References, Objects, and Modules
859       course taught by instructors for Stonehenge Consulting Services, Inc.
860       and used with permission.
861
862       Portions of this text have been derived from materials originally
863       appearing in Linux Magazine and used with permission.
864
865
866
867perl v5.10.1                      2009-05-14                       PERLBOOT(1)
Impressum