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