Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / man / man1 / perlboot.1
CommitLineData
86530b38
AT
1.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLBOOT 1"
132.TH PERLBOOT 1 "2002-06-08" "perl v5.8.0" "Perl Programmers Reference Guide"
133.SH "NAME"
134perlboot \- Beginner's Object\-Oriented Tutorial
135.SH "DESCRIPTION"
136.IX Header "DESCRIPTION"
137If you're not familiar with objects from other languages, some of the
138other Perl object documentation may be a little daunting, such as
139perlobj, a basic reference in using objects, and perltoot, which
140introduces readers to the peculiarities of Perl's object system in a
141tutorial way.
142.PP
143So, let's take a different approach, presuming no prior object
144experience. It helps if you know about subroutines (perlsub),
145references (perlref et. seq.), and packages (perlmod), so become
146familiar with those first if you haven't already.
147.Sh "If we could talk to the animals..."
148.IX Subsection "If we could talk to the animals..."
149Let's let the animals talk for a moment:
150.PP
151.Vb 9
152\& sub Cow::speak {
153\& print "a Cow goes moooo!\en";
154\& }
155\& sub Horse::speak {
156\& print "a Horse goes neigh!\en";
157\& }
158\& sub Sheep::speak {
159\& print "a Sheep goes baaaah!\en"
160\& }
161.Ve
162.PP
163.Vb 3
164\& Cow::speak;
165\& Horse::speak;
166\& Sheep::speak;
167.Ve
168.PP
169This results in:
170.PP
171.Vb 3
172\& a Cow goes moooo!
173\& a Horse goes neigh!
174\& a Sheep goes baaaah!
175.Ve
176.PP
177Nothing spectacular here. Simple subroutines, albeit from separate
178packages, and called using the full package name. So let's create
179an entire pasture:
180.PP
181.Vb 5
182\& # Cow::speak, Horse::speak, Sheep::speak as before
183\& @pasture = qw(Cow Cow Horse Sheep Sheep);
184\& foreach $animal (@pasture) {
185\& &{$animal."::speak"};
186\& }
187.Ve
188.PP
189This results in:
190.PP
191.Vb 5
192\& a Cow goes moooo!
193\& a Cow goes moooo!
194\& a Horse goes neigh!
195\& a Sheep goes baaaah!
196\& a Sheep goes baaaah!
197.Ve
198.PP
199Wow. That symbolic coderef de-referencing there is pretty nasty.
200We're counting on \f(CW\*(C`no strict subs\*(C'\fR mode, certainly not recommended
201for larger programs. And why was that necessary? Because the name of
202the package seems to be inseparable from the name of the subroutine we
203want to invoke within that package.
204.PP
205Or is it?
206.Sh "Introducing the method invocation arrow"
207.IX Subsection "Introducing the method invocation arrow"
208For now, let's say that \f(CW\*(C`Class\->method\*(C'\fR invokes subroutine
209\&\f(CW\*(C`method\*(C'\fR in package \f(CW\*(C`Class\*(C'\fR. (Here, \*(L"Class\*(R" is used in its
210\&\*(L"category\*(R" meaning, not its \*(L"scholastic\*(R" meaning.) That's not
211completely accurate, but we'll do this one step at a time. Now let's
212use it like so:
213.PP
214.Vb 4
215\& # Cow::speak, Horse::speak, Sheep::speak as before
216\& Cow->speak;
217\& Horse->speak;
218\& Sheep->speak;
219.Ve
220.PP
221And once again, this results in:
222.PP
223.Vb 3
224\& a Cow goes moooo!
225\& a Horse goes neigh!
226\& a Sheep goes baaaah!
227.Ve
228.PP
229That's not fun yet. Same number of characters, all constant, no
230variables. But yet, the parts are separable now. Watch:
231.PP
232.Vb 2
233\& $a = "Cow";
234\& $a->speak; # invokes Cow->speak
235.Ve
236.PP
237Ahh! Now that the package name has been parted from the subroutine
238name, we can use a variable package name. And this time, we've got
239something that works even when \f(CW\*(C`use strict refs\*(C'\fR is enabled.
240.Sh "Invoking a barnyard"
241.IX Subsection "Invoking a barnyard"
242Let's take that new arrow invocation and put it back in the barnyard
243example:
244.PP
245.Vb 9
246\& sub Cow::speak {
247\& print "a Cow goes moooo!\en";
248\& }
249\& sub Horse::speak {
250\& print "a Horse goes neigh!\en";
251\& }
252\& sub Sheep::speak {
253\& print "a Sheep goes baaaah!\en"
254\& }
255.Ve
256.PP
257.Vb 4
258\& @pasture = qw(Cow Cow Horse Sheep Sheep);
259\& foreach $animal (@pasture) {
260\& $animal->speak;
261\& }
262.Ve
263.PP
264There! Now we have the animals all talking, and safely at that,
265without the use of symbolic coderefs.
266.PP
267But look at all that common code. Each of the \f(CW\*(C`speak\*(C'\fR routines has a
268similar structure: a \f(CW\*(C`print\*(C'\fR operator and a string that contains
269common text, except for two of the words. It'd be nice if we could
270factor out the commonality, in case we decide later to change it all
271to \f(CW\*(C`says\*(C'\fR instead of \f(CW\*(C`goes\*(C'\fR.
272.PP
273And we actually have a way of doing that without much fuss, but we
274have to hear a bit more about what the method invocation arrow is
275actually doing for us.
276.Sh "The extra parameter of method invocation"
277.IX Subsection "The extra parameter of method invocation"
278The invocation of:
279.PP
280.Vb 1
281\& Class->method(@args)
282.Ve
283.PP
284attempts to invoke subroutine \f(CW\*(C`Class::method\*(C'\fR as:
285.PP
286.Vb 1
287\& Class::method("Class", @args);
288.Ve
289.PP
290(If the subroutine can't be found, \*(L"inheritance\*(R" kicks in, but we'll
291get to that later.) This means that we get the class name as the
292first parameter (the only parameter, if no arguments are given). So
293we can rewrite the \f(CW\*(C`Sheep\*(C'\fR speaking subroutine as:
294.PP
295.Vb 4
296\& sub Sheep::speak {
297\& my $class = shift;
298\& print "a $class goes baaaah!\en";
299\& }
300.Ve
301.PP
302And the other two animals come out similarly:
303.PP
304.Vb 8
305\& sub Cow::speak {
306\& my $class = shift;
307\& print "a $class goes moooo!\en";
308\& }
309\& sub Horse::speak {
310\& my $class = shift;
311\& print "a $class goes neigh!\en";
312\& }
313.Ve
314.PP
315In each case, \f(CW$class\fR will get the value appropriate for that
316subroutine. But once again, we have a lot of similar structure. Can
317we factor that out even further? Yes, by calling another method in
318the same class.
319.Sh "Calling a second method to simplify things"
320.IX Subsection "Calling a second method to simplify things"
321Let's call out from \f(CW\*(C`speak\*(C'\fR to a helper method called \f(CW\*(C`sound\*(C'\fR.
322This method provides the constant text for the sound itself.
323.PP
324.Vb 7
325\& { package Cow;
326\& sub sound { "moooo" }
327\& sub speak {
328\& my $class = shift;
329\& print "a $class goes ", $class->sound, "!\en"
330\& }
331\& }
332.Ve
333.PP
334Now, when we call \f(CW\*(C`Cow\->speak\*(C'\fR, we get a \f(CW$class\fR of \f(CW\*(C`Cow\*(C'\fR in
335\&\f(CW\*(C`speak\*(C'\fR. This in turn selects the \f(CW\*(C`Cow\->sound\*(C'\fR method, which
336returns \f(CW\*(C`moooo\*(C'\fR. But how different would this be for the \f(CW\*(C`Horse\*(C'\fR?
337.PP
338.Vb 7
339\& { package Horse;
340\& sub sound { "neigh" }
341\& sub speak {
342\& my $class = shift;
343\& print "a $class goes ", $class->sound, "!\en"
344\& }
345\& }
346.Ve
347.PP
348Only the name of the package and the specific sound change. So can we
349somehow share the definition for \f(CW\*(C`speak\*(C'\fR between the Cow and the
350Horse? Yes, with inheritance!
351.Sh "Inheriting the windpipes"
352.IX Subsection "Inheriting the windpipes"
353We'll define a common subroutine package called \f(CW\*(C`Animal\*(C'\fR, with the
354definition for \f(CW\*(C`speak\*(C'\fR:
355.PP
356.Vb 6
357\& { package Animal;
358\& sub speak {
359\& my $class = shift;
360\& print "a $class goes ", $class->sound, "!\en"
361\& }
362\& }
363.Ve
364.PP
365Then, for each animal, we say it \*(L"inherits\*(R" from \f(CW\*(C`Animal\*(C'\fR, along
366with the animal-specific sound:
367.PP
368.Vb 4
369\& { package Cow;
370\& @ISA = qw(Animal);
371\& sub sound { "moooo" }
372\& }
373.Ve
374.PP
375Note the added \f(CW@ISA\fR array. We'll get to that in a minute.
376.PP
377But what happens when we invoke \f(CW\*(C`Cow\->speak\*(C'\fR now?
378.PP
379First, Perl constructs the argument list. In this case, it's just
380\&\f(CW\*(C`Cow\*(C'\fR. Then Perl looks for \f(CW\*(C`Cow::speak\*(C'\fR. But that's not there, so
381Perl checks for the inheritance array \f(CW@Cow::ISA\fR. It's there,
382and contains the single name \f(CW\*(C`Animal\*(C'\fR.
383.PP
384Perl next checks for \f(CW\*(C`speak\*(C'\fR inside \f(CW\*(C`Animal\*(C'\fR instead, as in
385\&\f(CW\*(C`Animal::speak\*(C'\fR. And that's found, so Perl invokes that subroutine
386with the already frozen argument list.
387.PP
388Inside the \f(CW\*(C`Animal::speak\*(C'\fR subroutine, \f(CW$class\fR becomes \f(CW\*(C`Cow\*(C'\fR (the
389first argument). So when we get to the step of invoking
390\&\f(CW\*(C`$class\->sound\*(C'\fR, it'll be looking for \f(CW\*(C`Cow\->sound\*(C'\fR, which
391gets it on the first try without looking at \f(CW@ISA\fR. Success!
392.ie n .Sh "A few notes about @ISA"
393.el .Sh "A few notes about \f(CW@ISA\fP"
394.IX Subsection "A few notes about @ISA"
395This magical \f(CW@ISA\fR variable (pronounced \*(L"is a\*(R" not \*(L"ice\-uh\*(R"), has
396declared that \f(CW\*(C`Cow\*(C'\fR \*(L"is a\*(R" \f(CW\*(C`Animal\*(C'\fR. Note that it's an array,
397not a simple single value, because on rare occasions, it makes sense
398to have more than one parent class searched for the missing methods.
399.PP
400If \f(CW\*(C`Animal\*(C'\fR also had an \f(CW@ISA\fR, then we'd check there too. The
401search is recursive, depth\-first, left-to-right in each \f(CW@ISA\fR.
402Typically, each \f(CW@ISA\fR has only one element (multiple elements means
403multiple inheritance and multiple headaches), so we get a nice tree of
404inheritance.
405.PP
406When we turn on \f(CW\*(C`use strict\*(C'\fR, we'll get complaints on \f(CW@ISA\fR, since
407it's not a variable containing an explicit package name, nor is it a
408lexical (\*(L"my\*(R") variable. We can't make it a lexical variable though
409(it has to belong to the package to be found by the inheritance mechanism),
410so there's a couple of straightforward ways to handle that.
411.PP
412The easiest is to just spell the package name out:
413.PP
414.Vb 1
415\& @Cow::ISA = qw(Animal);
416.Ve
417.PP
418Or allow it as an implicitly named package variable:
419.PP
420.Vb 3
421\& package Cow;
422\& use vars qw(@ISA);
423\& @ISA = qw(Animal);
424.Ve
425.PP
426If you're bringing in the class from outside, via an object-oriented
427module, you change:
428.PP
429.Vb 4
430\& package Cow;
431\& use Animal;
432\& use vars qw(@ISA);
433\& @ISA = qw(Animal);
434.Ve
435.PP
436into just:
437.PP
438.Vb 2
439\& package Cow;
440\& use base qw(Animal);
441.Ve
442.PP
443And that's pretty darn compact.
444.Sh "Overriding the methods"
445.IX Subsection "Overriding the methods"
446Let's add a mouse, which can barely be heard:
447.PP
448.Vb 10
449\& # Animal package from before
450\& { package Mouse;
451\& @ISA = qw(Animal);
452\& sub sound { "squeak" }
453\& sub speak {
454\& my $class = shift;
455\& print "a $class goes ", $class->sound, "!\en";
456\& print "[but you can barely hear it!]\en";
457\& }
458\& }
459.Ve
460.PP
461.Vb 1
462\& Mouse->speak;
463.Ve
464.PP
465which results in:
466.PP
467.Vb 2
468\& a Mouse goes squeak!
469\& [but you can barely hear it!]
470.Ve
471.PP
472Here, \f(CW\*(C`Mouse\*(C'\fR has its own speaking routine, so \f(CW\*(C`Mouse\->speak\*(C'\fR
473doesn't immediately invoke \f(CW\*(C`Animal\->speak\*(C'\fR. This is known as
474\&\*(L"overriding\*(R". In fact, we didn't even need to say that a \f(CW\*(C`Mouse\*(C'\fR was
475an \f(CW\*(C`Animal\*(C'\fR at all, since all of the methods needed for \f(CW\*(C`speak\*(C'\fR are
476completely defined with \f(CW\*(C`Mouse\*(C'\fR.
477.PP
478But we've now duplicated some of the code from \f(CW\*(C`Animal\->speak\*(C'\fR,
479and this can once again be a maintenance headache. So, can we avoid
480that? Can we say somehow that a \f(CW\*(C`Mouse\*(C'\fR does everything any other
481\&\f(CW\*(C`Animal\*(C'\fR does, but add in the extra comment? Sure!
482.PP
483First, we can invoke the \f(CW\*(C`Animal::speak\*(C'\fR method directly:
484.PP
485.Vb 10
486\& # Animal package from before
487\& { package Mouse;
488\& @ISA = qw(Animal);
489\& sub sound { "squeak" }
490\& sub speak {
491\& my $class = shift;
492\& Animal::speak($class);
493\& print "[but you can barely hear it!]\en";
494\& }
495\& }
496.Ve
497.PP
498Note that we have to include the \f(CW$class\fR parameter (almost surely
499the value of \f(CW"Mouse"\fR) as the first parameter to \f(CW\*(C`Animal::speak\*(C'\fR,
500since we've stopped using the method arrow. Why did we stop? Well,
501if we invoke \f(CW\*(C`Animal\->speak\*(C'\fR there, the first parameter to the
502method will be \f(CW"Animal"\fR not \f(CW"Mouse"\fR, and when time comes for it
503to call for the \f(CW\*(C`sound\*(C'\fR, it won't have the right class to come back
504to this package.
505.PP
506Invoking \f(CW\*(C`Animal::speak\*(C'\fR directly is a mess, however. What if
507\&\f(CW\*(C`Animal::speak\*(C'\fR didn't exist before, and was being inherited from a
508class mentioned in \f(CW@Animal::ISA\fR? Because we are no longer using
509the method arrow, we get one and only one chance to hit the right
510subroutine.
511.PP
512Also note that the \f(CW\*(C`Animal\*(C'\fR classname is now hardwired into the
513subroutine selection. This is a mess if someone maintains the code,
514changing \f(CW@ISA\fR for <Mouse> and didn't notice \f(CW\*(C`Animal\*(C'\fR there in
515\&\f(CW\*(C`speak\*(C'\fR. So, this is probably not the right way to go.
516.Sh "Starting the search from a different place"
517.IX Subsection "Starting the search from a different place"
518A better solution is to tell Perl to search from a higher place
519in the inheritance chain:
520.PP
521.Vb 9
522\& # same Animal as before
523\& { package Mouse;
524\& # same @ISA, &sound as before
525\& sub speak {
526\& my $class = shift;
527\& $class->Animal::speak;
528\& print "[but you can barely hear it!]\en";
529\& }
530\& }
531.Ve
532.PP
533Ahh. This works. Using this syntax, we start with \f(CW\*(C`Animal\*(C'\fR to find
534\&\f(CW\*(C`speak\*(C'\fR, and use all of \f(CW\*(C`Animal\*(C'\fR's inheritance chain if not found
535immediately. And yet the first parameter will be \f(CW$class\fR, so the
536found \f(CW\*(C`speak\*(C'\fR method will get \f(CW\*(C`Mouse\*(C'\fR as its first entry, and
537eventually work its way back to \f(CW\*(C`Mouse::sound\*(C'\fR for the details.
538.PP
539But this isn't the best solution. We still have to keep the \f(CW@ISA\fR
540and the initial search package coordinated. Worse, if \f(CW\*(C`Mouse\*(C'\fR had
541multiple entries in \f(CW@ISA\fR, we wouldn't necessarily know which one
542had actually defined \f(CW\*(C`speak\*(C'\fR. So, is there an even better way?
543.Sh "The \s-1SUPER\s0 way of doing things"
544.IX Subsection "The SUPER way of doing things"
545By changing the \f(CW\*(C`Animal\*(C'\fR class to the \f(CW\*(C`SUPER\*(C'\fR class in that
546invocation, we get a search of all of our super classes (classes
547listed in \f(CW@ISA\fR) automatically:
548.PP
549.Vb 9
550\& # same Animal as before
551\& { package Mouse;
552\& # same @ISA, &sound as before
553\& sub speak {
554\& my $class = shift;
555\& $class->SUPER::speak;
556\& print "[but you can barely hear it!]\en";
557\& }
558\& }
559.Ve
560.PP
561So, \f(CW\*(C`SUPER::speak\*(C'\fR means look in the current package's \f(CW@ISA\fR for
562\&\f(CW\*(C`speak\*(C'\fR, invoking the first one found.
563.Sh "Where we're at so far..."
564.IX Subsection "Where we're at so far..."
565So far, we've seen the method arrow syntax:
566.PP
567.Vb 1
568\& Class->method(@args);
569.Ve
570.PP
571or the equivalent:
572.PP
573.Vb 2
574\& $a = "Class";
575\& $a->method(@args);
576.Ve
577.PP
578which constructs an argument list of:
579.PP
580.Vb 1
581\& ("Class", @args)
582.Ve
583.PP
584and attempts to invoke
585.PP
586.Vb 1
587\& Class::method("Class", @Args);
588.Ve
589.PP
590However, if \f(CW\*(C`Class::method\*(C'\fR is not found, then \f(CW@Class::ISA\fR is examined
591(recursively) to locate a package that does indeed contain \f(CW\*(C`method\*(C'\fR,
592and that subroutine is invoked instead.
593.PP
594Using this simple syntax, we have class methods, (multiple)
595inheritance, overriding, and extending. Using just what we've seen so
596far, we've been able to factor out common code, and provide a nice way
597to reuse implementations with variations. This is at the core of what
598objects provide, but objects also provide instance data, which we
599haven't even begun to cover.
600.Sh "A horse is a horse, of course of course \*(-- or is it?"
601.IX Subsection "A horse is a horse, of course of course or is it?"
602Let's start with the code for the \f(CW\*(C`Animal\*(C'\fR class
603and the \f(CW\*(C`Horse\*(C'\fR class:
604.PP
605.Vb 10
606\& { package Animal;
607\& sub speak {
608\& my $class = shift;
609\& print "a $class goes ", $class->sound, "!\en"
610\& }
611\& }
612\& { package Horse;
613\& @ISA = qw(Animal);
614\& sub sound { "neigh" }
615\& }
616.Ve
617.PP
618This lets us invoke \f(CW\*(C`Horse\->speak\*(C'\fR to ripple upward to
619\&\f(CW\*(C`Animal::speak\*(C'\fR, calling back to \f(CW\*(C`Horse::sound\*(C'\fR to get the specific
620sound, and the output of:
621.PP
622.Vb 1
623\& a Horse goes neigh!
624.Ve
625.PP
626But all of our Horse objects would have to be absolutely identical.
627If I add a subroutine, all horses automatically share it. That's
628great for making horses the same, but how do we capture the
629distinctions about an individual horse? For example, suppose I want
630to give my first horse a name. There's got to be a way to keep its
631name separate from the other horses.
632.PP
633We can do that by drawing a new distinction, called an \*(L"instance\*(R".
634An \*(L"instance\*(R" is generally created by a class. In Perl, any reference
635can be an instance, so let's start with the simplest reference
636that can hold a horse's name: a scalar reference.
637.PP
638.Vb 2
639\& my $name = "Mr. Ed";
640\& my $talking = \e$name;
641.Ve
642.PP
643So now \f(CW$talking\fR is a reference to what will be the instance-specific
644data (the name). The final step in turning this into a real instance
645is with a special operator called \f(CW\*(C`bless\*(C'\fR:
646.PP
647.Vb 1
648\& bless $talking, Horse;
649.Ve
650.PP
651This operator stores information about the package named \f(CW\*(C`Horse\*(C'\fR into
652the thing pointed at by the reference. At this point, we say
653\&\f(CW$talking\fR is an instance of \f(CW\*(C`Horse\*(C'\fR. That is, it's a specific
654horse. The reference is otherwise unchanged, and can still be used
655with traditional dereferencing operators.
656.Sh "Invoking an instance method"
657.IX Subsection "Invoking an instance method"
658The method arrow can be used on instances, as well as names of
659packages (classes). So, let's get the sound that \f(CW$talking\fR makes:
660.PP
661.Vb 1
662\& my $noise = $talking->sound;
663.Ve
664.PP
665To invoke \f(CW\*(C`sound\*(C'\fR, Perl first notes that \f(CW$talking\fR is a blessed
666reference (and thus an instance). It then constructs an argument
667list, in this case from just \f(CW\*(C`($talking)\*(C'\fR. (Later we'll see that
668arguments will take their place following the instance variable,
669just like with classes.)
670.PP
671Now for the fun part: Perl takes the class in which the instance was
672blessed, in this case \f(CW\*(C`Horse\*(C'\fR, and uses that to locate the subroutine
673to invoke the method. In this case, \f(CW\*(C`Horse::sound\*(C'\fR is found directly
674(without using inheritance), yielding the final subroutine invocation:
675.PP
676.Vb 1
677\& Horse::sound($talking)
678.Ve
679.PP
680Note that the first parameter here is still the instance, not the name
681of the class as before. We'll get \f(CW\*(C`neigh\*(C'\fR as the return value, and
682that'll end up as the \f(CW$noise\fR variable above.
683.PP
684If Horse::sound had not been found, we'd be wandering up the
685\&\f(CW@Horse::ISA\fR list to try to find the method in one of the
686superclasses, just as for a class method. The only difference between
687a class method and an instance method is whether the first parameter
688is an instance (a blessed reference) or a class name (a string).
689.Sh "Accessing the instance data"
690.IX Subsection "Accessing the instance data"
691Because we get the instance as the first parameter, we can now access
692the instance-specific data. In this case, let's add a way to get at
693the name:
694.PP
695.Vb 8
696\& { package Horse;
697\& @ISA = qw(Animal);
698\& sub sound { "neigh" }
699\& sub name {
700\& my $self = shift;
701\& $$self;
702\& }
703\& }
704.Ve
705.PP
706Now we call for the name:
707.PP
708.Vb 1
709\& print $talking->name, " says ", $talking->sound, "\en";
710.Ve
711.PP
712Inside \f(CW\*(C`Horse::name\*(C'\fR, the \f(CW@_\fR array contains just \f(CW$talking\fR,
713which the \f(CW\*(C`shift\*(C'\fR stores into \f(CW$self\fR. (It's traditional to shift
714the first parameter off into a variable named \f(CW$self\fR for instance
715methods, so stay with that unless you have strong reasons otherwise.)
716Then, \f(CW$self\fR gets de-referenced as a scalar ref, yielding \f(CW\*(C`Mr. Ed\*(C'\fR,
717and we're done with that. The result is:
718.PP
719.Vb 1
720\& Mr. Ed says neigh.
721.Ve
722.Sh "How to build a horse"
723.IX Subsection "How to build a horse"
724Of course, if we constructed all of our horses by hand, we'd most
725likely make mistakes from time to time. We're also violating one of
726the properties of object-oriented programming, in that the \*(L"inside
727guts\*(R" of a Horse are visible. That's good if you're a veterinarian,
728but not if you just like to own horses. So, let's let the Horse class
729build a new horse:
730.PP
731.Vb 13
732\& { package Horse;
733\& @ISA = qw(Animal);
734\& sub sound { "neigh" }
735\& sub name {
736\& my $self = shift;
737\& $$self;
738\& }
739\& sub named {
740\& my $class = shift;
741\& my $name = shift;
742\& bless \e$name, $class;
743\& }
744\& }
745.Ve
746.PP
747Now with the new \f(CW\*(C`named\*(C'\fR method, we can build a horse:
748.PP
749.Vb 1
750\& my $talking = Horse->named("Mr. Ed");
751.Ve
752.PP
753Notice we're back to a class method, so the two arguments to
754\&\f(CW\*(C`Horse::named\*(C'\fR are \f(CW\*(C`Horse\*(C'\fR and \f(CW\*(C`Mr. Ed\*(C'\fR. The \f(CW\*(C`bless\*(C'\fR operator
755not only blesses \f(CW$name\fR, it also returns the reference to \f(CW$name\fR,
756so that's fine as a return value. And that's how to build a horse.
757.PP
758We've called the constructor \f(CW\*(C`named\*(C'\fR here, so that it quickly denotes
759the constructor's argument as the name for this particular \f(CW\*(C`Horse\*(C'\fR.
760You can use different constructors with different names for different
761ways of \*(L"giving birth\*(R" to the object (like maybe recording its
762pedigree or date of birth). However, you'll find that most people
763coming to Perl from more limited languages use a single constructor
764named \f(CW\*(C`new\*(C'\fR, with various ways of interpreting the arguments to
765\&\f(CW\*(C`new\*(C'\fR. Either style is fine, as long as you document your particular
766way of giving birth to an object. (And you \fIwere\fR going to do that,
767right?)
768.Sh "Inheriting the constructor"
769.IX Subsection "Inheriting the constructor"
770But was there anything specific to \f(CW\*(C`Horse\*(C'\fR in that method? No. Therefore,
771it's also the same recipe for building anything else that inherited from
772\&\f(CW\*(C`Animal\*(C'\fR, so let's put it there:
773.PP
774.Vb 19
775\& { package Animal;
776\& sub speak {
777\& my $class = shift;
778\& print "a $class goes ", $class->sound, "!\en"
779\& }
780\& sub name {
781\& my $self = shift;
782\& $$self;
783\& }
784\& sub named {
785\& my $class = shift;
786\& my $name = shift;
787\& bless \e$name, $class;
788\& }
789\& }
790\& { package Horse;
791\& @ISA = qw(Animal);
792\& sub sound { "neigh" }
793\& }
794.Ve
795.PP
796Ahh, but what happens if we invoke \f(CW\*(C`speak\*(C'\fR on an instance?
797.PP
798.Vb 2
799\& my $talking = Horse->named("Mr. Ed");
800\& $talking->speak;
801.Ve
802.PP
803We get a debugging value:
804.PP
805.Vb 1
806\& a Horse=SCALAR(0xaca42ac) goes neigh!
807.Ve
808.PP
809Why? Because the \f(CW\*(C`Animal::speak\*(C'\fR routine is expecting a classname as
810its first parameter, not an instance. When the instance is passed in,
811we'll end up using a blessed scalar reference as a string, and that
812shows up as we saw it just now.
813.Sh "Making a method work with either classes or instances"
814.IX Subsection "Making a method work with either classes or instances"
815All we need is for a method to detect if it is being called on a class
816or called on an instance. The most straightforward way is with the
817\&\f(CW\*(C`ref\*(C'\fR operator. This returns a string (the classname) when used on a
818blessed reference, and \f(CW\*(C`undef\*(C'\fR when used on a string (like a
819classname). Let's modify the \f(CW\*(C`name\*(C'\fR method first to notice the change:
820.PP
821.Vb 6
822\& sub name {
823\& my $either = shift;
824\& ref $either
825\& ? $$either # it's an instance, return name
826\& : "an unnamed $either"; # it's a class, return generic
827\& }
828.Ve
829.PP
830Here, the \f(CW\*(C`?:\*(C'\fR operator comes in handy to select either the
831dereference or a derived string. Now we can use this with either an
832instance or a class. Note that I've changed the first parameter
833holder to \f(CW$either\fR to show that this is intended:
834.PP
835.Vb 3
836\& my $talking = Horse->named("Mr. Ed");
837\& print Horse->name, "\en"; # prints "an unnamed Horse\en"
838\& print $talking->name, "\en"; # prints "Mr Ed.\en"
839.Ve
840.PP
841and now we'll fix \f(CW\*(C`speak\*(C'\fR to use this:
842.PP
843.Vb 4
844\& sub speak {
845\& my $either = shift;
846\& print $either->name, " goes ", $either->sound, "\en";
847\& }
848.Ve
849.PP
850And since \f(CW\*(C`sound\*(C'\fR already worked with either a class or an instance,
851we're done!
852.Sh "Adding parameters to a method"
853.IX Subsection "Adding parameters to a method"
854Let's train our animals to eat:
855.PP
856.Vb 30
857\& { package Animal;
858\& sub named {
859\& my $class = shift;
860\& my $name = shift;
861\& bless \e$name, $class;
862\& }
863\& sub name {
864\& my $either = shift;
865\& ref $either
866\& ? $$either # it's an instance, return name
867\& : "an unnamed $either"; # it's a class, return generic
868\& }
869\& sub speak {
870\& my $either = shift;
871\& print $either->name, " goes ", $either->sound, "\en";
872\& }
873\& sub eat {
874\& my $either = shift;
875\& my $food = shift;
876\& print $either->name, " eats $food.\en";
877\& }
878\& }
879\& { package Horse;
880\& @ISA = qw(Animal);
881\& sub sound { "neigh" }
882\& }
883\& { package Sheep;
884\& @ISA = qw(Animal);
885\& sub sound { "baaaah" }
886\& }
887.Ve
888.PP
889And now try it out:
890.PP
891.Vb 3
892\& my $talking = Horse->named("Mr. Ed");
893\& $talking->eat("hay");
894\& Sheep->eat("grass");
895.Ve
896.PP
897which prints:
898.PP
899.Vb 2
900\& Mr. Ed eats hay.
901\& an unnamed Sheep eats grass.
902.Ve
903.PP
904An instance method with parameters gets invoked with the instance,
905and then the list of parameters. So that first invocation is like:
906.PP
907.Vb 1
908\& Animal::eat($talking, "hay");
909.Ve
910.Sh "More interesting instances"
911.IX Subsection "More interesting instances"
912What if an instance needs more data? Most interesting instances are
913made of many items, each of which can in turn be a reference or even
914another object. The easiest way to store these is often in a hash.
915The keys of the hash serve as the names of parts of the object (often
916called \*(L"instance variables\*(R" or \*(L"member variables\*(R"), and the
917corresponding values are, well, the values.
918.PP
919But how do we turn the horse into a hash? Recall that an object was
920any blessed reference. We can just as easily make it a blessed hash
921reference as a blessed scalar reference, as long as everything that
922looks at the reference is changed accordingly.
923.PP
924Let's make a sheep that has a name and a color:
925.PP
926.Vb 1
927\& my $bad = bless { Name => "Evil", Color => "black" }, Sheep;
928.Ve
929.PP
930so \f(CW\*(C`$bad\->{Name}\*(C'\fR has \f(CW\*(C`Evil\*(C'\fR, and \f(CW\*(C`$bad\->{Color}\*(C'\fR has
931\&\f(CW\*(C`black\*(C'\fR. But we want to make \f(CW\*(C`$bad\->name\*(C'\fR access the name, and
932that's now messed up because it's expecting a scalar reference. Not
933to worry, because that's pretty easy to fix up:
934.PP
935.Vb 7
936\& ## in Animal
937\& sub name {
938\& my $either = shift;
939\& ref $either ?
940\& $either->{Name} :
941\& "an unnamed $either";
942\& }
943.Ve
944.PP
945And of course \f(CW\*(C`named\*(C'\fR still builds a scalar sheep, so let's fix that
946as well:
947.PP
948.Vb 7
949\& ## in Animal
950\& sub named {
951\& my $class = shift;
952\& my $name = shift;
953\& my $self = { Name => $name, Color => $class->default_color };
954\& bless $self, $class;
955\& }
956.Ve
957.PP
958What's this \f(CW\*(C`default_color\*(C'\fR? Well, if \f(CW\*(C`named\*(C'\fR has only the name,
959we still need to set a color, so we'll have a class-specific initial color.
960For a sheep, we might define it as white:
961.PP
962.Vb 2
963\& ## in Sheep
964\& sub default_color { "white" }
965.Ve
966.PP
967And then to keep from having to define one for each additional class,
968we'll define a \*(L"backstop\*(R" method that serves as the \*(L"default default\*(R",
969directly in \f(CW\*(C`Animal\*(C'\fR:
970.PP
971.Vb 2
972\& ## in Animal
973\& sub default_color { "brown" }
974.Ve
975.PP
976Now, because \f(CW\*(C`name\*(C'\fR and \f(CW\*(C`named\*(C'\fR were the only methods that
977referenced the \*(L"structure\*(R" of the object, the rest of the methods can
978remain the same, so \f(CW\*(C`speak\*(C'\fR still works as before.
979.Sh "A horse of a different color"
980.IX Subsection "A horse of a different color"
981But having all our horses be brown would be boring. So let's add a
982method or two to get and set the color.
983.PP
984.Vb 7
985\& ## in Animal
986\& sub color {
987\& $_[0]->{Color}
988\& }
989\& sub set_color {
990\& $_[0]->{Color} = $_[1];
991\& }
992.Ve
993.PP
994Note the alternate way of accessing the arguments: \f(CW$_[0]\fR is used
995in\-place, rather than with a \f(CW\*(C`shift\*(C'\fR. (This saves us a bit of time
996for something that may be invoked frequently.) And now we can fix
997that color for Mr. Ed:
998.PP
999.Vb 3
1000\& my $talking = Horse->named("Mr. Ed");
1001\& $talking->set_color("black-and-white");
1002\& print $talking->name, " is colored ", $talking->color, "\en";
1003.Ve
1004.PP
1005which results in:
1006.PP
1007.Vb 1
1008\& Mr. Ed is colored black-and-white
1009.Ve
1010.Sh "Summary"
1011.IX Subsection "Summary"
1012So, now we have class methods, constructors, instance methods,
1013instance data, and even accessors. But that's still just the
1014beginning of what Perl has to offer. We haven't even begun to talk
1015about accessors that double as getters and setters, destructors,
1016indirect object notation, subclasses that add instance data, per-class
1017data, overloading, \*(L"isa\*(R" and \*(L"can\*(R" tests, \f(CW\*(C`UNIVERSAL\*(C'\fR class, and so
1018on. That's for the rest of the Perl documentation to cover.
1019Hopefully, this gets you started, though.
1020.SH "SEE ALSO"
1021.IX Header "SEE ALSO"
1022For more information, see perlobj (for all the gritty details about
1023Perl objects, now that you've seen the basics), perltoot (the
1024tutorial for those who already know objects), perltooc (dealing
1025with class data), perlbot (for some more tricks), and books such as
1026Damian Conway's excellent \fIObject Oriented Perl\fR.
1027.PP
1028Some modules which might prove interesting are Class::Accessor,
1029Class::Class, Class::Contract, Class::Data::Inheritable,
1030Class::MethodMaker and Tie::SecureHash
1031.SH "COPYRIGHT"
1032.IX Header "COPYRIGHT"
1033Copyright (c) 1999, 2000 by Randal L. Schwartz and Stonehenge
1034Consulting Services, Inc. Permission is hereby granted to distribute
1035this document intact with the Perl distribution, and in accordance
1036with the licenses of the Perl distribution; derived documents must
1037include this copyright notice intact.
1038.PP
1039Portions of this text have been derived from Perl Training materials
1040originally appearing in the \fIPackages, References, Objects, and
1041Modules\fR course taught by instructors for Stonehenge Consulting
1042Services, Inc. and used with permission.
1043.PP
1044Portions of this text have been derived from materials originally
1045appearing in \fILinux Magazine\fR and used with permission.