Commit | Line | Data |
---|---|---|
920dae64 AT |
1 | .\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32 |
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 "PERLTOOT 1" | |
132 | .TH PERLTOOT 1 "2006-01-07" "perl v5.8.8" "Perl Programmers Reference Guide" | |
133 | .SH "NAME" | |
134 | perltoot \- Tom's object\-oriented tutorial for perl | |
135 | .SH "DESCRIPTION" | |
136 | .IX Header "DESCRIPTION" | |
137 | Object-oriented programming is a big seller these days. Some managers | |
138 | would rather have objects than sliced bread. Why is that? What's so | |
139 | special about an object? Just what \fIis\fR an object anyway? | |
140 | .PP | |
141 | An object is nothing but a way of tucking away complex behaviours into | |
142 | a neat little easy-to-use bundle. (This is what professors call | |
143 | abstraction.) Smart people who have nothing to do but sit around for | |
144 | weeks on end figuring out really hard problems make these nifty | |
145 | objects that even regular people can use. (This is what professors call | |
146 | software reuse.) Users (well, programmers) can play with this little | |
147 | bundle all they want, but they aren't to open it up and mess with the | |
148 | insides. Just like an expensive piece of hardware, the contract says | |
149 | that you void the warranty if you muck with the cover. So don't do that. | |
150 | .PP | |
151 | The heart of objects is the class, a protected little private namespace | |
152 | full of data and functions. A class is a set of related routines that | |
153 | addresses some problem area. You can think of it as a user-defined type. | |
154 | The Perl package mechanism, also used for more traditional modules, | |
155 | is used for class modules as well. Objects \*(L"live\*(R" in a class, meaning | |
156 | that they belong to some package. | |
157 | .PP | |
158 | More often than not, the class provides the user with little bundles. | |
159 | These bundles are objects. They know whose class they belong to, | |
160 | and how to behave. Users ask the class to do something, like \*(L"give | |
161 | me an object.\*(R" Or they can ask one of these objects to do something. | |
162 | Asking a class to do something for you is calling a \fIclass method\fR. | |
163 | Asking an object to do something for you is calling an \fIobject method\fR. | |
164 | Asking either a class (usually) or an object (sometimes) to give you | |
165 | back an object is calling a \fIconstructor\fR, which is just a | |
166 | kind of method. | |
167 | .PP | |
168 | That's all well and good, but how is an object different from any other | |
169 | Perl data type? Just what is an object \fIreally\fR; that is, what's its | |
170 | fundamental type? The answer to the first question is easy. An object | |
171 | is different from any other data type in Perl in one and only one way: | |
172 | you may dereference it using not merely string or numeric subscripts | |
173 | as with simple arrays and hashes, but with named subroutine calls. | |
174 | In a word, with \fImethods\fR. | |
175 | .PP | |
176 | The answer to the second question is that it's a reference, and not just | |
177 | any reference, mind you, but one whose referent has been \fIbless\fR()ed | |
178 | into a particular class (read: package). What kind of reference? Well, | |
179 | the answer to that one is a bit less concrete. That's because in Perl | |
180 | the designer of the class can employ any sort of reference they'd like | |
181 | as the underlying intrinsic data type. It could be a scalar, an array, | |
182 | or a hash reference. It could even be a code reference. But because | |
183 | of its inherent flexibility, an object is usually a hash reference. | |
184 | .SH "Creating a Class" | |
185 | .IX Header "Creating a Class" | |
186 | Before you create a class, you need to decide what to name it. That's | |
187 | because the class (package) name governs the name of the file used to | |
188 | house it, just as with regular modules. Then, that class (package) | |
189 | should provide one or more ways to generate objects. Finally, it should | |
190 | provide mechanisms to allow users of its objects to indirectly manipulate | |
191 | these objects from a distance. | |
192 | .PP | |
193 | For example, let's make a simple Person class module. It gets stored in | |
194 | the file Person.pm. If it were called a Happy::Person class, it would | |
195 | be stored in the file Happy/Person.pm, and its package would become | |
196 | Happy::Person instead of just Person. (On a personal computer not | |
197 | running Unix or Plan 9, but something like Mac \s-1OS\s0 or \s-1VMS\s0, the directory | |
198 | separator may be different, but the principle is the same.) Do not assume | |
199 | any formal relationship between modules based on their directory names. | |
200 | This is merely a grouping convenience, and has no effect on inheritance, | |
201 | variable accessibility, or anything else. | |
202 | .PP | |
203 | For this module we aren't going to use Exporter, because we're | |
204 | a well-behaved class module that doesn't export anything at all. | |
205 | In order to manufacture objects, a class needs to have a \fIconstructor | |
206 | method\fR. A constructor gives you back not just a regular data type, | |
207 | but a brand-new object in that class. This magic is taken care of by | |
208 | the \fIbless()\fR function, whose sole purpose is to enable its referent to | |
209 | be used as an object. Remember: being an object really means nothing | |
210 | more than that methods may now be called against it. | |
211 | .PP | |
212 | While a constructor may be named anything you'd like, most Perl | |
213 | programmers seem to like to call theirs \fInew()\fR. However, \fInew()\fR is not | |
214 | a reserved word, and a class is under no obligation to supply such. | |
215 | Some programmers have also been known to use a function with | |
216 | the same name as the class as the constructor. | |
217 | .Sh "Object Representation" | |
218 | .IX Subsection "Object Representation" | |
219 | By far the most common mechanism used in Perl to represent a Pascal | |
220 | record, a C struct, or a \*(C+ class is an anonymous hash. That's because a | |
221 | hash has an arbitrary number of data fields, each conveniently accessed by | |
222 | an arbitrary name of your own devising. | |
223 | .PP | |
224 | If you were just doing a simple | |
225 | struct-like emulation, you would likely go about it something like this: | |
226 | .PP | |
227 | .Vb 5 | |
228 | \& $rec = { | |
229 | \& name => "Jason", | |
230 | \& age => 23, | |
231 | \& peers => [ "Norbert", "Rhys", "Phineas"], | |
232 | \& }; | |
233 | .Ve | |
234 | .PP | |
235 | If you felt like it, you could add a bit of visual distinction | |
236 | by up-casing the hash keys: | |
237 | .PP | |
238 | .Vb 5 | |
239 | \& $rec = { | |
240 | \& NAME => "Jason", | |
241 | \& AGE => 23, | |
242 | \& PEERS => [ "Norbert", "Rhys", "Phineas"], | |
243 | \& }; | |
244 | .Ve | |
245 | .PP | |
246 | And so you could get at \f(CW\*(C`$rec\->{NAME}\*(C'\fR to find \*(L"Jason\*(R", or | |
247 | \&\f(CW\*(C`@{ $rec\->{PEERS} }\*(C'\fR to get at \*(L"Norbert\*(R", \*(L"Rhys\*(R", and \*(L"Phineas\*(R". | |
248 | (Have you ever noticed how many 23\-year\-old programmers seem to | |
249 | be named \*(L"Jason\*(R" these days? :\-) | |
250 | .PP | |
251 | This same model is often used for classes, although it is not considered | |
252 | the pinnacle of programming propriety for folks from outside the | |
253 | class to come waltzing into an object, brazenly accessing its data | |
254 | members directly. Generally speaking, an object should be considered | |
255 | an opaque cookie that you use \fIobject methods\fR to access. Visually, | |
256 | methods look like you're dereffing a reference using a function name | |
257 | instead of brackets or braces. | |
258 | .Sh "Class Interface" | |
259 | .IX Subsection "Class Interface" | |
260 | Some languages provide a formal syntactic interface to a class's methods, | |
261 | but Perl does not. It relies on you to read the documentation of each | |
262 | class. If you try to call an undefined method on an object, Perl won't | |
263 | complain, but the program will trigger an exception while it's running. | |
264 | Likewise, if you call a method expecting a prime number as its argument | |
265 | with a non-prime one instead, you can't expect the compiler to catch this. | |
266 | (Well, you can expect it all you like, but it's not going to happen.) | |
267 | .PP | |
268 | Let's suppose you have a well-educated user of your Person class, | |
269 | someone who has read the docs that explain the prescribed | |
270 | interface. Here's how they might use the Person class: | |
271 | .PP | |
272 | .Vb 1 | |
273 | \& use Person; | |
274 | .Ve | |
275 | .PP | |
276 | .Vb 4 | |
277 | \& $him = Person->new(); | |
278 | \& $him->name("Jason"); | |
279 | \& $him->age(23); | |
280 | \& $him->peers( "Norbert", "Rhys", "Phineas" ); | |
281 | .Ve | |
282 | .PP | |
283 | .Vb 1 | |
284 | \& push @All_Recs, $him; # save object in array for later | |
285 | .Ve | |
286 | .PP | |
287 | .Vb 2 | |
288 | \& printf "%s is %d years old.\en", $him->name, $him->age; | |
289 | \& print "His peers are: ", join(", ", $him->peers), "\en"; | |
290 | .Ve | |
291 | .PP | |
292 | .Vb 1 | |
293 | \& printf "Last rec's name is %s\en", $All_Recs[-1]->name; | |
294 | .Ve | |
295 | .PP | |
296 | As you can see, the user of the class doesn't know (or at least, has no | |
297 | business paying attention to the fact) that the object has one particular | |
298 | implementation or another. The interface to the class and its objects | |
299 | is exclusively via methods, and that's all the user of the class should | |
300 | ever play with. | |
301 | .Sh "Constructors and Instance Methods" | |
302 | .IX Subsection "Constructors and Instance Methods" | |
303 | Still, \fIsomeone\fR has to know what's in the object. And that someone is | |
304 | the class. It implements methods that the programmer uses to access | |
305 | the object. Here's how to implement the Person class using the standard | |
306 | hash-ref-as-an-object idiom. We'll make a class method called \fInew()\fR to | |
307 | act as the constructor, and three object methods called \fIname()\fR, \fIage()\fR, and | |
308 | \&\fIpeers()\fR to get at per-object data hidden away in our anonymous hash. | |
309 | .PP | |
310 | .Vb 2 | |
311 | \& package Person; | |
312 | \& use strict; | |
313 | .Ve | |
314 | .PP | |
315 | .Vb 11 | |
316 | \& ################################################## | |
317 | \& ## the object constructor (simplistic version) ## | |
318 | \& ################################################## | |
319 | \& sub new { | |
320 | \& my $self = {}; | |
321 | \& $self->{NAME} = undef; | |
322 | \& $self->{AGE} = undef; | |
323 | \& $self->{PEERS} = []; | |
324 | \& bless($self); # but see below | |
325 | \& return $self; | |
326 | \& } | |
327 | .Ve | |
328 | .PP | |
329 | .Vb 6 | |
330 | \& ############################################## | |
331 | \& ## methods to access per-object data ## | |
332 | \& ## ## | |
333 | \& ## With args, they set the value. Without ## | |
334 | \& ## any, they only retrieve it/them. ## | |
335 | \& ############################################## | |
336 | .Ve | |
337 | .PP | |
338 | .Vb 5 | |
339 | \& sub name { | |
340 | \& my $self = shift; | |
341 | \& if (@_) { $self->{NAME} = shift } | |
342 | \& return $self->{NAME}; | |
343 | \& } | |
344 | .Ve | |
345 | .PP | |
346 | .Vb 5 | |
347 | \& sub age { | |
348 | \& my $self = shift; | |
349 | \& if (@_) { $self->{AGE} = shift } | |
350 | \& return $self->{AGE}; | |
351 | \& } | |
352 | .Ve | |
353 | .PP | |
354 | .Vb 5 | |
355 | \& sub peers { | |
356 | \& my $self = shift; | |
357 | \& if (@_) { @{ $self->{PEERS} } = @_ } | |
358 | \& return @{ $self->{PEERS} }; | |
359 | \& } | |
360 | .Ve | |
361 | .PP | |
362 | .Vb 1 | |
363 | \& 1; # so the require or use succeeds | |
364 | .Ve | |
365 | .PP | |
366 | We've created three methods to access an object's data, \fIname()\fR, \fIage()\fR, | |
367 | and \fIpeers()\fR. These are all substantially similar. If called with an | |
368 | argument, they set the appropriate field; otherwise they return the | |
369 | value held by that field, meaning the value of that hash key. | |
370 | .Sh "Planning for the Future: Better Constructors" | |
371 | .IX Subsection "Planning for the Future: Better Constructors" | |
372 | Even though at this point you may not even know what it means, someday | |
373 | you're going to worry about inheritance. (You can safely ignore this | |
374 | for now and worry about it later if you'd like.) To ensure that this | |
375 | all works out smoothly, you must use the double-argument form of \fIbless()\fR. | |
376 | The second argument is the class into which the referent will be blessed. | |
377 | By not assuming our own class as the default second argument and instead | |
378 | using the class passed into us, we make our constructor inheritable. | |
379 | .PP | |
380 | .Vb 9 | |
381 | \& sub new { | |
382 | \& my $class = shift; | |
383 | \& my $self = {}; | |
384 | \& $self->{NAME} = undef; | |
385 | \& $self->{AGE} = undef; | |
386 | \& $self->{PEERS} = []; | |
387 | \& bless ($self, $class); | |
388 | \& return $self; | |
389 | \& } | |
390 | .Ve | |
391 | .PP | |
392 | That's about all there is for constructors. These methods bring objects | |
393 | to life, returning neat little opaque bundles to the user to be used in | |
394 | subsequent method calls. | |
395 | .Sh "Destructors" | |
396 | .IX Subsection "Destructors" | |
397 | Every story has a beginning and an end. The beginning of the object's | |
398 | story is its constructor, explicitly called when the object comes into | |
399 | existence. But the ending of its story is the \fIdestructor\fR, a method | |
400 | implicitly called when an object leaves this life. Any per-object | |
401 | clean-up code is placed in the destructor, which must (in Perl) be called | |
402 | \&\s-1DESTROY\s0. | |
403 | .PP | |
404 | If constructors can have arbitrary names, then why not destructors? | |
405 | Because while a constructor is explicitly called, a destructor is not. | |
406 | Destruction happens automatically via Perl's garbage collection (\s-1GC\s0) | |
407 | system, which is a quick but somewhat lazy reference-based \s-1GC\s0 system. | |
408 | To know what to call, Perl insists that the destructor be named \s-1DESTROY\s0. | |
409 | Perl's notion of the right time to call a destructor is not well-defined | |
410 | currently, which is why your destructors should not rely on when they are | |
411 | called. | |
412 | .PP | |
413 | Why is \s-1DESTROY\s0 in all caps? Perl on occasion uses purely uppercase | |
414 | function names as a convention to indicate that the function will | |
415 | be automatically called by Perl in some way. Others that are called | |
416 | implicitly include \s-1BEGIN\s0, \s-1END\s0, \s-1AUTOLOAD\s0, plus all methods used by | |
417 | tied objects, described in perltie. | |
418 | .PP | |
419 | In really good object-oriented programming languages, the user doesn't | |
420 | care when the destructor is called. It just happens when it's supposed | |
421 | to. In low-level languages without any \s-1GC\s0 at all, there's no way to | |
422 | depend on this happening at the right time, so the programmer must | |
423 | explicitly call the destructor to clean up memory and state, crossing | |
424 | their fingers that it's the right time to do so. Unlike \*(C+, an | |
425 | object destructor is nearly never needed in Perl, and even when it is, | |
426 | explicit invocation is uncalled for. In the case of our Person class, | |
427 | we don't need a destructor because Perl takes care of simple matters | |
428 | like memory deallocation. | |
429 | .PP | |
430 | The only situation where Perl's reference-based \s-1GC\s0 won't work is | |
431 | when there's a circularity in the data structure, such as: | |
432 | .PP | |
433 | .Vb 1 | |
434 | \& $this->{WHATEVER} = $this; | |
435 | .Ve | |
436 | .PP | |
437 | In that case, you must delete the self-reference manually if you expect | |
438 | your program not to leak memory. While admittedly error\-prone, this is | |
439 | the best we can do right now. Nonetheless, rest assured that when your | |
440 | program is finished, its objects' destructors are all duly called. | |
441 | So you are guaranteed that an object \fIeventually\fR gets properly | |
442 | destroyed, except in the unique case of a program that never exits. | |
443 | (If you're running Perl embedded in another application, this full \s-1GC\s0 | |
444 | pass happens a bit more frequently\*(--whenever a thread shuts down.) | |
445 | .Sh "Other Object Methods" | |
446 | .IX Subsection "Other Object Methods" | |
447 | The methods we've talked about so far have either been constructors or | |
448 | else simple \*(L"data methods\*(R", interfaces to data stored in the object. | |
449 | These are a bit like an object's data members in the \*(C+ world, except | |
450 | that strangers don't access them as data. Instead, they should only | |
451 | access the object's data indirectly via its methods. This is an | |
452 | important rule: in Perl, access to an object's data should \fIonly\fR | |
453 | be made through methods. | |
454 | .PP | |
455 | Perl doesn't impose restrictions on who gets to use which methods. | |
456 | The public-versus-private distinction is by convention, not syntax. | |
457 | (Well, unless you use the Alias module described below in | |
458 | \&\*(L"Data Members as Variables\*(R".) Occasionally you'll see method names beginning or ending | |
459 | with an underscore or two. This marking is a convention indicating | |
460 | that the methods are private to that class alone and sometimes to its | |
461 | closest acquaintances, its immediate subclasses. But this distinction | |
462 | is not enforced by Perl itself. It's up to the programmer to behave. | |
463 | .PP | |
464 | There's no reason to limit methods to those that simply access data. | |
465 | Methods can do anything at all. The key point is that they're invoked | |
466 | against an object or a class. Let's say we'd like object methods that | |
467 | do more than fetch or set one particular field. | |
468 | .PP | |
469 | .Vb 5 | |
470 | \& sub exclaim { | |
471 | \& my $self = shift; | |
472 | \& return sprintf "Hi, I'm %s, age %d, working with %s", | |
473 | \& $self->{NAME}, $self->{AGE}, join(", ", @{$self->{PEERS}}); | |
474 | \& } | |
475 | .Ve | |
476 | .PP | |
477 | Or maybe even one like this: | |
478 | .PP | |
479 | .Vb 4 | |
480 | \& sub happy_birthday { | |
481 | \& my $self = shift; | |
482 | \& return ++$self->{AGE}; | |
483 | \& } | |
484 | .Ve | |
485 | .PP | |
486 | Some might argue that one should go at these this way: | |
487 | .PP | |
488 | .Vb 5 | |
489 | \& sub exclaim { | |
490 | \& my $self = shift; | |
491 | \& return sprintf "Hi, I'm %s, age %d, working with %s", | |
492 | \& $self->name, $self->age, join(", ", $self->peers); | |
493 | \& } | |
494 | .Ve | |
495 | .PP | |
496 | .Vb 4 | |
497 | \& sub happy_birthday { | |
498 | \& my $self = shift; | |
499 | \& return $self->age( $self->age() + 1 ); | |
500 | \& } | |
501 | .Ve | |
502 | .PP | |
503 | But since these methods are all executing in the class itself, this | |
504 | may not be critical. There are tradeoffs to be made. Using direct | |
505 | hash access is faster (about an order of magnitude faster, in fact), and | |
506 | it's more convenient when you want to interpolate in strings. But using | |
507 | methods (the external interface) internally shields not just the users of | |
508 | your class but even you yourself from changes in your data representation. | |
509 | .SH "Class Data" | |
510 | .IX Header "Class Data" | |
511 | What about \*(L"class data\*(R", data items common to each object in a class? | |
512 | What would you want that for? Well, in your Person class, you might | |
513 | like to keep track of the total people alive. How do you implement that? | |
514 | .PP | |
515 | You \fIcould\fR make it a global variable called \f(CW$Person::Census\fR. But about | |
516 | only reason you'd do that would be if you \fIwanted\fR people to be able to | |
517 | get at your class data directly. They could just say \f(CW$Person::Census\fR | |
518 | and play around with it. Maybe this is ok in your design scheme. | |
519 | You might even conceivably want to make it an exported variable. To be | |
520 | exportable, a variable must be a (package) global. If this were a | |
521 | traditional module rather than an object-oriented one, you might do that. | |
522 | .PP | |
523 | While this approach is expected in most traditional modules, it's | |
524 | generally considered rather poor form in most object modules. In an | |
525 | object module, you should set up a protective veil to separate interface | |
526 | from implementation. So provide a class method to access class data | |
527 | just as you provide object methods to access object data. | |
528 | .PP | |
529 | So, you \fIcould\fR still keep \f(CW$Census\fR as a package global and rely upon | |
530 | others to honor the contract of the module and therefore not play around | |
531 | with its implementation. You could even be supertricky and make \f(CW$Census\fR a | |
532 | tied object as described in perltie, thereby intercepting all accesses. | |
533 | .PP | |
534 | But more often than not, you just want to make your class data a | |
535 | file-scoped lexical. To do so, simply put this at the top of the file: | |
536 | .PP | |
537 | .Vb 1 | |
538 | \& my $Census = 0; | |
539 | .Ve | |
540 | .PP | |
541 | Even though the scope of a \fImy()\fR normally expires when the block in which | |
542 | it was declared is done (in this case the whole file being required or | |
543 | used), Perl's deep binding of lexical variables guarantees that the | |
544 | variable will not be deallocated, remaining accessible to functions | |
545 | declared within that scope. This doesn't work with global variables | |
546 | given temporary values via \fIlocal()\fR, though. | |
547 | .PP | |
548 | Irrespective of whether you leave \f(CW$Census\fR a package global or make | |
549 | it instead a file-scoped lexical, you should make these | |
550 | changes to your \fIPerson::new()\fR constructor: | |
551 | .PP | |
552 | .Vb 10 | |
553 | \& sub new { | |
554 | \& my $class = shift; | |
555 | \& my $self = {}; | |
556 | \& $Census++; | |
557 | \& $self->{NAME} = undef; | |
558 | \& $self->{AGE} = undef; | |
559 | \& $self->{PEERS} = []; | |
560 | \& bless ($self, $class); | |
561 | \& return $self; | |
562 | \& } | |
563 | .Ve | |
564 | .PP | |
565 | .Vb 3 | |
566 | \& sub population { | |
567 | \& return $Census; | |
568 | \& } | |
569 | .Ve | |
570 | .PP | |
571 | Now that we've done this, we certainly do need a destructor so that | |
572 | when Person is destroyed, the \f(CW$Census\fR goes down. Here's how | |
573 | this could be done: | |
574 | .PP | |
575 | .Vb 1 | |
576 | \& sub DESTROY { --$Census } | |
577 | .Ve | |
578 | .PP | |
579 | Notice how there's no memory to deallocate in the destructor? That's | |
580 | something that Perl takes care of for you all by itself. | |
581 | .PP | |
582 | Alternatively, you could use the Class::Data::Inheritable module from | |
583 | \&\s-1CPAN\s0. | |
584 | .Sh "Accessing Class Data" | |
585 | .IX Subsection "Accessing Class Data" | |
586 | It turns out that this is not really a good way to go about handling | |
587 | class data. A good scalable rule is that \fIyou must never reference class | |
588 | data directly from an object method\fR. Otherwise you aren't building a | |
589 | scalable, inheritable class. The object must be the rendezvous point | |
590 | for all operations, especially from an object method. The globals | |
591 | (class data) would in some sense be in the \*(L"wrong\*(R" package in your | |
592 | derived classes. In Perl, methods execute in the context of the class | |
593 | they were defined in, \fInot\fR that of the object that triggered them. | |
594 | Therefore, namespace visibility of package globals in methods is unrelated | |
595 | to inheritance. | |
596 | .PP | |
597 | Got that? Maybe not. Ok, let's say that some other class \*(L"borrowed\*(R" | |
598 | (well, inherited) the \s-1DESTROY\s0 method as it was defined above. When those | |
599 | objects are destroyed, the original \f(CW$Census\fR variable will be altered, | |
600 | not the one in the new class's package namespace. Perhaps this is what | |
601 | you want, but probably it isn't. | |
602 | .PP | |
603 | Here's how to fix this. We'll store a reference to the data in the | |
604 | value accessed by the hash key \*(L"_CENSUS\*(R". Why the underscore? Well, | |
605 | mostly because an initial underscore already conveys strong feelings | |
606 | of magicalness to a C programmer. It's really just a mnemonic device | |
607 | to remind ourselves that this field is special and not to be used as | |
608 | a public data member in the same way that \s-1NAME\s0, \s-1AGE\s0, and \s-1PEERS\s0 are. | |
609 | (Because we've been developing this code under the strict pragma, prior | |
610 | to perl version 5.004 we'll have to quote the field name.) | |
611 | .PP | |
612 | .Vb 12 | |
613 | \& sub new { | |
614 | \& my $class = shift; | |
615 | \& my $self = {}; | |
616 | \& $self->{NAME} = undef; | |
617 | \& $self->{AGE} = undef; | |
618 | \& $self->{PEERS} = []; | |
619 | \& # "private" data | |
620 | \& $self->{"_CENSUS"} = \e$Census; | |
621 | \& bless ($self, $class); | |
622 | \& ++ ${ $self->{"_CENSUS"} }; | |
623 | \& return $self; | |
624 | \& } | |
625 | .Ve | |
626 | .PP | |
627 | .Vb 8 | |
628 | \& sub population { | |
629 | \& my $self = shift; | |
630 | \& if (ref $self) { | |
631 | \& return ${ $self->{"_CENSUS"} }; | |
632 | \& } else { | |
633 | \& return $Census; | |
634 | \& } | |
635 | \& } | |
636 | .Ve | |
637 | .PP | |
638 | .Vb 4 | |
639 | \& sub DESTROY { | |
640 | \& my $self = shift; | |
641 | \& -- ${ $self->{"_CENSUS"} }; | |
642 | \& } | |
643 | .Ve | |
644 | .Sh "Debugging Methods" | |
645 | .IX Subsection "Debugging Methods" | |
646 | It's common for a class to have a debugging mechanism. For example, | |
647 | you might want to see when objects are created or destroyed. To do that, | |
648 | add a debugging variable as a file-scoped lexical. For this, we'll pull | |
649 | in the standard Carp module to emit our warnings and fatal messages. | |
650 | That way messages will come out with the caller's filename and | |
651 | line number instead of our own; if we wanted them to be from our own | |
652 | perspective, we'd just use \fIdie()\fR and \fIwarn()\fR directly instead of \fIcroak()\fR | |
653 | and \fIcarp()\fR respectively. | |
654 | .PP | |
655 | .Vb 2 | |
656 | \& use Carp; | |
657 | \& my $Debugging = 0; | |
658 | .Ve | |
659 | .PP | |
660 | Now add a new class method to access the variable. | |
661 | .PP | |
662 | .Vb 6 | |
663 | \& sub debug { | |
664 | \& my $class = shift; | |
665 | \& if (ref $class) { confess "Class method called as object method" } | |
666 | \& unless (@_ == 1) { confess "usage: CLASSNAME->debug(level)" } | |
667 | \& $Debugging = shift; | |
668 | \& } | |
669 | .Ve | |
670 | .PP | |
671 | Now fix up \s-1DESTROY\s0 to murmur a bit as the moribund object expires: | |
672 | .PP | |
673 | .Vb 5 | |
674 | \& sub DESTROY { | |
675 | \& my $self = shift; | |
676 | \& if ($Debugging) { carp "Destroying $self " . $self->name } | |
677 | \& -- ${ $self->{"_CENSUS"} }; | |
678 | \& } | |
679 | .Ve | |
680 | .PP | |
681 | One could conceivably make a per-object debug state. That | |
682 | way you could call both of these: | |
683 | .PP | |
684 | .Vb 2 | |
685 | \& Person->debug(1); # entire class | |
686 | \& $him->debug(1); # just this object | |
687 | .Ve | |
688 | .PP | |
689 | To do so, we need our debugging method to be a \*(L"bimodal\*(R" one, one that | |
690 | works on both classes \fIand\fR objects. Therefore, adjust the \fIdebug()\fR | |
691 | and \s-1DESTROY\s0 methods as follows: | |
692 | .PP | |
693 | .Vb 10 | |
694 | \& sub debug { | |
695 | \& my $self = shift; | |
696 | \& confess "usage: thing->debug(level)" unless @_ == 1; | |
697 | \& my $level = shift; | |
698 | \& if (ref($self)) { | |
699 | \& $self->{"_DEBUG"} = $level; # just myself | |
700 | \& } else { | |
701 | \& $Debugging = $level; # whole class | |
702 | \& } | |
703 | \& } | |
704 | .Ve | |
705 | .PP | |
706 | .Vb 7 | |
707 | \& sub DESTROY { | |
708 | \& my $self = shift; | |
709 | \& if ($Debugging || $self->{"_DEBUG"}) { | |
710 | \& carp "Destroying $self " . $self->name; | |
711 | \& } | |
712 | \& -- ${ $self->{"_CENSUS"} }; | |
713 | \& } | |
714 | .Ve | |
715 | .PP | |
716 | What happens if a derived class (which we'll call Employee) inherits | |
717 | methods from this Person base class? Then \f(CW\*(C`Employee\->debug()\*(C'\fR, when called | |
718 | as a class method, manipulates \f(CW$Person::Debugging\fR not \f(CW$Employee::Debugging\fR. | |
719 | .Sh "Class Destructors" | |
720 | .IX Subsection "Class Destructors" | |
721 | The object destructor handles the death of each distinct object. But sometimes | |
722 | you want a bit of cleanup when the entire class is shut down, which | |
723 | currently only happens when the program exits. To make such a | |
724 | \&\fIclass destructor\fR, create a function in that class's package named | |
725 | \&\s-1END\s0. This works just like the \s-1END\s0 function in traditional modules, | |
726 | meaning that it gets called whenever your program exits unless it execs | |
727 | or dies of an uncaught signal. For example, | |
728 | .PP | |
729 | .Vb 5 | |
730 | \& sub END { | |
731 | \& if ($Debugging) { | |
732 | \& print "All persons are going away now.\en"; | |
733 | \& } | |
734 | \& } | |
735 | .Ve | |
736 | .PP | |
737 | When the program exits, all the class destructors (\s-1END\s0 functions) are | |
738 | be called in the opposite order that they were loaded in (\s-1LIFO\s0 order). | |
739 | .Sh "Documenting the Interface" | |
740 | .IX Subsection "Documenting the Interface" | |
741 | And there you have it: we've just shown you the \fIimplementation\fR of this | |
742 | Person class. Its \fIinterface\fR would be its documentation. Usually this | |
743 | means putting it in pod (\*(L"plain old documentation\*(R") format right there | |
744 | in the same file. In our Person example, we would place the following | |
745 | docs anywhere in the Person.pm file. Even though it looks mostly like | |
746 | code, it's not. It's embedded documentation such as would be used by | |
747 | the pod2man, pod2html, or pod2text programs. The Perl compiler ignores | |
748 | pods entirely, just as the translators ignore code. Here's an example of | |
749 | some pods describing the informal interface: | |
750 | .PP | |
751 | .Vb 1 | |
752 | \& =head1 NAME | |
753 | .Ve | |
754 | .PP | |
755 | .Vb 1 | |
756 | \& Person - class to implement people | |
757 | .Ve | |
758 | .PP | |
759 | .Vb 1 | |
760 | \& =head1 SYNOPSIS | |
761 | .Ve | |
762 | .PP | |
763 | .Vb 1 | |
764 | \& use Person; | |
765 | .Ve | |
766 | .PP | |
767 | .Vb 5 | |
768 | \& ################# | |
769 | \& # class methods # | |
770 | \& ################# | |
771 | \& $ob = Person->new; | |
772 | \& $count = Person->population; | |
773 | .Ve | |
774 | .PP | |
775 | .Vb 3 | |
776 | \& ####################### | |
777 | \& # object data methods # | |
778 | \& ####################### | |
779 | .Ve | |
780 | .PP | |
781 | .Vb 4 | |
782 | \& ### get versions ### | |
783 | \& $who = $ob->name; | |
784 | \& $years = $ob->age; | |
785 | \& @pals = $ob->peers; | |
786 | .Ve | |
787 | .PP | |
788 | .Vb 4 | |
789 | \& ### set versions ### | |
790 | \& $ob->name("Jason"); | |
791 | \& $ob->age(23); | |
792 | \& $ob->peers( "Norbert", "Rhys", "Phineas" ); | |
793 | .Ve | |
794 | .PP | |
795 | .Vb 3 | |
796 | \& ######################## | |
797 | \& # other object methods # | |
798 | \& ######################## | |
799 | .Ve | |
800 | .PP | |
801 | .Vb 2 | |
802 | \& $phrase = $ob->exclaim; | |
803 | \& $ob->happy_birthday; | |
804 | .Ve | |
805 | .PP | |
806 | .Vb 1 | |
807 | \& =head1 DESCRIPTION | |
808 | .Ve | |
809 | .PP | |
810 | .Vb 1 | |
811 | \& The Person class implements dah dee dah dee dah.... | |
812 | .Ve | |
813 | .PP | |
814 | That's all there is to the matter of interface versus implementation. | |
815 | A programmer who opens up the module and plays around with all the private | |
816 | little shiny bits that were safely locked up behind the interface contract | |
817 | has voided the warranty, and you shouldn't worry about their fate. | |
818 | .SH "Aggregation" | |
819 | .IX Header "Aggregation" | |
820 | Suppose you later want to change the class to implement better names. | |
821 | Perhaps you'd like to support both given names (called Christian names, | |
822 | irrespective of one's religion) and family names (called surnames), plus | |
823 | nicknames and titles. If users of your Person class have been properly | |
824 | accessing it through its documented interface, then you can easily change | |
825 | the underlying implementation. If they haven't, then they lose and | |
826 | it's their fault for breaking the contract and voiding their warranty. | |
827 | .PP | |
828 | To do this, we'll make another class, this one called Fullname. What's | |
829 | the Fullname class look like? To answer that question, you have to | |
830 | first figure out how you want to use it. How about we use it this way: | |
831 | .PP | |
832 | .Vb 7 | |
833 | \& $him = Person->new(); | |
834 | \& $him->fullname->title("St"); | |
835 | \& $him->fullname->christian("Thomas"); | |
836 | \& $him->fullname->surname("Aquinas"); | |
837 | \& $him->fullname->nickname("Tommy"); | |
838 | \& printf "His normal name is %s\en", $him->name; | |
839 | \& printf "But his real name is %s\en", $him->fullname->as_string; | |
840 | .Ve | |
841 | .PP | |
842 | Ok. To do this, we'll change \fIPerson::new()\fR so that it supports | |
843 | a full name field this way: | |
844 | .PP | |
845 | .Vb 11 | |
846 | \& sub new { | |
847 | \& my $class = shift; | |
848 | \& my $self = {}; | |
849 | \& $self->{FULLNAME} = Fullname->new(); | |
850 | \& $self->{AGE} = undef; | |
851 | \& $self->{PEERS} = []; | |
852 | \& $self->{"_CENSUS"} = \e$Census; | |
853 | \& bless ($self, $class); | |
854 | \& ++ ${ $self->{"_CENSUS"} }; | |
855 | \& return $self; | |
856 | \& } | |
857 | .Ve | |
858 | .PP | |
859 | .Vb 4 | |
860 | \& sub fullname { | |
861 | \& my $self = shift; | |
862 | \& return $self->{FULLNAME}; | |
863 | \& } | |
864 | .Ve | |
865 | .PP | |
866 | Then to support old code, define \fIPerson::name()\fR this way: | |
867 | .PP | |
868 | .Vb 5 | |
869 | \& sub name { | |
870 | \& my $self = shift; | |
871 | \& return $self->{FULLNAME}->nickname(@_) | |
872 | \& || $self->{FULLNAME}->christian(@_); | |
873 | \& } | |
874 | .Ve | |
875 | .PP | |
876 | Here's the Fullname class. We'll use the same technique | |
877 | of using a hash reference to hold data fields, and methods | |
878 | by the appropriate name to access them: | |
879 | .PP | |
880 | .Vb 2 | |
881 | \& package Fullname; | |
882 | \& use strict; | |
883 | .Ve | |
884 | .PP | |
885 | .Vb 11 | |
886 | \& sub new { | |
887 | \& my $class = shift; | |
888 | \& my $self = { | |
889 | \& TITLE => undef, | |
890 | \& CHRISTIAN => undef, | |
891 | \& SURNAME => undef, | |
892 | \& NICK => undef, | |
893 | \& }; | |
894 | \& bless ($self, $class); | |
895 | \& return $self; | |
896 | \& } | |
897 | .Ve | |
898 | .PP | |
899 | .Vb 5 | |
900 | \& sub christian { | |
901 | \& my $self = shift; | |
902 | \& if (@_) { $self->{CHRISTIAN} = shift } | |
903 | \& return $self->{CHRISTIAN}; | |
904 | \& } | |
905 | .Ve | |
906 | .PP | |
907 | .Vb 5 | |
908 | \& sub surname { | |
909 | \& my $self = shift; | |
910 | \& if (@_) { $self->{SURNAME} = shift } | |
911 | \& return $self->{SURNAME}; | |
912 | \& } | |
913 | .Ve | |
914 | .PP | |
915 | .Vb 5 | |
916 | \& sub nickname { | |
917 | \& my $self = shift; | |
918 | \& if (@_) { $self->{NICK} = shift } | |
919 | \& return $self->{NICK}; | |
920 | \& } | |
921 | .Ve | |
922 | .PP | |
923 | .Vb 5 | |
924 | \& sub title { | |
925 | \& my $self = shift; | |
926 | \& if (@_) { $self->{TITLE} = shift } | |
927 | \& return $self->{TITLE}; | |
928 | \& } | |
929 | .Ve | |
930 | .PP | |
931 | .Vb 8 | |
932 | \& sub as_string { | |
933 | \& my $self = shift; | |
934 | \& my $name = join(" ", @$self{'CHRISTIAN', 'SURNAME'}); | |
935 | \& if ($self->{TITLE}) { | |
936 | \& $name = $self->{TITLE} . " " . $name; | |
937 | \& } | |
938 | \& return $name; | |
939 | \& } | |
940 | .Ve | |
941 | .PP | |
942 | .Vb 1 | |
943 | \& 1; | |
944 | .Ve | |
945 | .PP | |
946 | Finally, here's the test program: | |
947 | .PP | |
948 | .Vb 4 | |
949 | \& #!/usr/bin/perl -w | |
950 | \& use strict; | |
951 | \& use Person; | |
952 | \& sub END { show_census() } | |
953 | .Ve | |
954 | .PP | |
955 | .Vb 3 | |
956 | \& sub show_census () { | |
957 | \& printf "Current population: %d\en", Person->population; | |
958 | \& } | |
959 | .Ve | |
960 | .PP | |
961 | .Vb 1 | |
962 | \& Person->debug(1); | |
963 | .Ve | |
964 | .PP | |
965 | .Vb 1 | |
966 | \& show_census(); | |
967 | .Ve | |
968 | .PP | |
969 | .Vb 1 | |
970 | \& my $him = Person->new(); | |
971 | .Ve | |
972 | .PP | |
973 | .Vb 5 | |
974 | \& $him->fullname->christian("Thomas"); | |
975 | \& $him->fullname->surname("Aquinas"); | |
976 | \& $him->fullname->nickname("Tommy"); | |
977 | \& $him->fullname->title("St"); | |
978 | \& $him->age(1); | |
979 | .Ve | |
980 | .PP | |
981 | .Vb 4 | |
982 | \& printf "%s is really %s.\en", $him->name, $him->fullname->as_string; | |
983 | \& printf "%s's age: %d.\en", $him->name, $him->age; | |
984 | \& $him->happy_birthday; | |
985 | \& printf "%s's age: %d.\en", $him->name, $him->age; | |
986 | .Ve | |
987 | .PP | |
988 | .Vb 1 | |
989 | \& show_census(); | |
990 | .Ve | |
991 | .SH "Inheritance" | |
992 | .IX Header "Inheritance" | |
993 | Object-oriented programming systems all support some notion of | |
994 | inheritance. Inheritance means allowing one class to piggy-back on | |
995 | top of another one so you don't have to write the same code again and | |
996 | again. It's about software reuse, and therefore related to Laziness, | |
997 | the principal virtue of a programmer. (The import/export mechanisms in | |
998 | traditional modules are also a form of code reuse, but a simpler one than | |
999 | the true inheritance that you find in object modules.) | |
1000 | .PP | |
1001 | Sometimes the syntax of inheritance is built into the core of the | |
1002 | language, and sometimes it's not. Perl has no special syntax for | |
1003 | specifying the class (or classes) to inherit from. Instead, it's all | |
1004 | strictly in the semantics. Each package can have a variable called \f(CW@ISA\fR, | |
1005 | which governs (method) inheritance. If you try to call a method on an | |
1006 | object or class, and that method is not found in that object's package, | |
1007 | Perl then looks to \f(CW@ISA\fR for other packages to go looking through in | |
1008 | search of the missing method. | |
1009 | .PP | |
1010 | Like the special per-package variables recognized by Exporter (such as | |
1011 | \&\f(CW@EXPORT\fR, \f(CW@EXPORT_OK\fR, \f(CW@EXPORT_FAIL\fR, \f(CW%EXPORT_TAGS\fR, and \f(CW$VERSION\fR), the \f(CW@ISA\fR | |
1012 | array \fImust\fR be a package-scoped global and not a file-scoped lexical | |
1013 | created via \fImy()\fR. Most classes have just one item in their \f(CW@ISA\fR array. | |
1014 | In this case, we have what's called \*(L"single inheritance\*(R", or \s-1SI\s0 for short. | |
1015 | .PP | |
1016 | Consider this class: | |
1017 | .PP | |
1018 | .Vb 4 | |
1019 | \& package Employee; | |
1020 | \& use Person; | |
1021 | \& @ISA = ("Person"); | |
1022 | \& 1; | |
1023 | .Ve | |
1024 | .PP | |
1025 | Not a lot to it, eh? All it's doing so far is loading in another | |
1026 | class and stating that this one will inherit methods from that | |
1027 | other class if need be. We have given it none of its own methods. | |
1028 | We rely upon an Employee to behave just like a Person. | |
1029 | .PP | |
1030 | Setting up an empty class like this is called the \*(L"empty subclass test\*(R"; | |
1031 | that is, making a derived class that does nothing but inherit from a | |
1032 | base class. If the original base class has been designed properly, | |
1033 | then the new derived class can be used as a drop-in replacement for the | |
1034 | old one. This means you should be able to write a program like this: | |
1035 | .PP | |
1036 | .Vb 5 | |
1037 | \& use Employee; | |
1038 | \& my $empl = Employee->new(); | |
1039 | \& $empl->name("Jason"); | |
1040 | \& $empl->age(23); | |
1041 | \& printf "%s is age %d.\en", $empl->name, $empl->age; | |
1042 | .Ve | |
1043 | .PP | |
1044 | By proper design, we mean always using the two-argument form of \fIbless()\fR, | |
1045 | avoiding direct access of global data, and not exporting anything. If you | |
1046 | look back at the \fIPerson::new()\fR function we defined above, we were careful | |
1047 | to do that. There's a bit of package data used in the constructor, | |
1048 | but the reference to this is stored on the object itself and all other | |
1049 | methods access package data via that reference, so we should be ok. | |
1050 | .PP | |
1051 | What do we mean by the \fIPerson::new()\fR function \*(-- isn't that actually | |
1052 | a method? Well, in principle, yes. A method is just a function that | |
1053 | expects as its first argument a class name (package) or object | |
1054 | (blessed reference). \fIPerson::new()\fR is the function that both the | |
1055 | \&\f(CW\*(C`Person\->new()\*(C'\fR method and the \f(CW\*(C`Employee\->new()\*(C'\fR method end | |
1056 | up calling. Understand that while a method call looks a lot like a | |
1057 | function call, they aren't really quite the same, and if you treat them | |
1058 | as the same, you'll very soon be left with nothing but broken programs. | |
1059 | First, the actual underlying calling conventions are different: method | |
1060 | calls get an extra argument. Second, function calls don't do inheritance, | |
1061 | but methods do. | |
1062 | .PP | |
1063 | .Vb 4 | |
1064 | \& Method Call Resulting Function Call | |
1065 | \& ----------- ------------------------ | |
1066 | \& Person->new() Person::new("Person") | |
1067 | \& Employee->new() Person::new("Employee") | |
1068 | .Ve | |
1069 | .PP | |
1070 | So don't use function calls when you mean to call a method. | |
1071 | .PP | |
1072 | If an employee is just a Person, that's not all too very interesting. | |
1073 | So let's add some other methods. We'll give our employee | |
1074 | data fields to access their salary, their employee \s-1ID\s0, and their | |
1075 | start date. | |
1076 | .PP | |
1077 | If you're getting a little tired of creating all these nearly identical | |
1078 | methods just to get at the object's data, do not despair. Later, | |
1079 | we'll describe several different convenience mechanisms for shortening | |
1080 | this up. Meanwhile, here's the straight-forward way: | |
1081 | .PP | |
1082 | .Vb 5 | |
1083 | \& sub salary { | |
1084 | \& my $self = shift; | |
1085 | \& if (@_) { $self->{SALARY} = shift } | |
1086 | \& return $self->{SALARY}; | |
1087 | \& } | |
1088 | .Ve | |
1089 | .PP | |
1090 | .Vb 5 | |
1091 | \& sub id_number { | |
1092 | \& my $self = shift; | |
1093 | \& if (@_) { $self->{ID} = shift } | |
1094 | \& return $self->{ID}; | |
1095 | \& } | |
1096 | .Ve | |
1097 | .PP | |
1098 | .Vb 5 | |
1099 | \& sub start_date { | |
1100 | \& my $self = shift; | |
1101 | \& if (@_) { $self->{START_DATE} = shift } | |
1102 | \& return $self->{START_DATE}; | |
1103 | \& } | |
1104 | .Ve | |
1105 | .Sh "Overridden Methods" | |
1106 | .IX Subsection "Overridden Methods" | |
1107 | What happens when both a derived class and its base class have the same | |
1108 | method defined? Well, then you get the derived class's version of that | |
1109 | method. For example, let's say that we want the \fIpeers()\fR method called on | |
1110 | an employee to act a bit differently. Instead of just returning the list | |
1111 | of peer names, let's return slightly different strings. So doing this: | |
1112 | .PP | |
1113 | .Vb 2 | |
1114 | \& $empl->peers("Peter", "Paul", "Mary"); | |
1115 | \& printf "His peers are: %s\en", join(", ", $empl->peers); | |
1116 | .Ve | |
1117 | .PP | |
1118 | will produce: | |
1119 | .PP | |
1120 | .Vb 1 | |
1121 | \& His peers are: PEON=PETER, PEON=PAUL, PEON=MARY | |
1122 | .Ve | |
1123 | .PP | |
1124 | To do this, merely add this definition into the Employee.pm file: | |
1125 | .PP | |
1126 | .Vb 5 | |
1127 | \& sub peers { | |
1128 | \& my $self = shift; | |
1129 | \& if (@_) { @{ $self->{PEERS} } = @_ } | |
1130 | \& return map { "PEON=\eU$_" } @{ $self->{PEERS} }; | |
1131 | \& } | |
1132 | .Ve | |
1133 | .PP | |
1134 | There, we've just demonstrated the high\-falutin' concept known in certain | |
1135 | circles as \fIpolymorphism\fR. We've taken on the form and behaviour of | |
1136 | an existing object, and then we've altered it to suit our own purposes. | |
1137 | This is a form of Laziness. (Getting polymorphed is also what happens | |
1138 | when the wizard decides you'd look better as a frog.) | |
1139 | .PP | |
1140 | Every now and then you'll want to have a method call trigger both its | |
1141 | derived class (also known as \*(L"subclass\*(R") version as well as its base class | |
1142 | (also known as \*(L"superclass\*(R") version. In practice, constructors and | |
1143 | destructors are likely to want to do this, and it probably also makes | |
1144 | sense in the \fIdebug()\fR method we showed previously. | |
1145 | .PP | |
1146 | To do this, add this to Employee.pm: | |
1147 | .PP | |
1148 | .Vb 2 | |
1149 | \& use Carp; | |
1150 | \& my $Debugging = 0; | |
1151 | .Ve | |
1152 | .PP | |
1153 | .Vb 11 | |
1154 | \& sub debug { | |
1155 | \& my $self = shift; | |
1156 | \& confess "usage: thing->debug(level)" unless @_ == 1; | |
1157 | \& my $level = shift; | |
1158 | \& if (ref($self)) { | |
1159 | \& $self->{"_DEBUG"} = $level; | |
1160 | \& } else { | |
1161 | \& $Debugging = $level; # whole class | |
1162 | \& } | |
1163 | \& Person::debug($self, $Debugging); # don't really do this | |
1164 | \& } | |
1165 | .Ve | |
1166 | .PP | |
1167 | As you see, we turn around and call the Person package's \fIdebug()\fR function. | |
1168 | But this is far too fragile for good design. What if Person doesn't | |
1169 | have a \fIdebug()\fR function, but is inheriting \fIits\fR \fIdebug()\fR method | |
1170 | from elsewhere? It would have been slightly better to say | |
1171 | .PP | |
1172 | .Vb 1 | |
1173 | \& Person->debug($Debugging); | |
1174 | .Ve | |
1175 | .PP | |
1176 | But even that's got too much hard\-coded. It's somewhat better to say | |
1177 | .PP | |
1178 | .Vb 1 | |
1179 | \& $self->Person::debug($Debugging); | |
1180 | .Ve | |
1181 | .PP | |
1182 | Which is a funny way to say to start looking for a \fIdebug()\fR method up | |
1183 | in Person. This strategy is more often seen on overridden object methods | |
1184 | than on overridden class methods. | |
1185 | .PP | |
1186 | There is still something a bit off here. We've hard-coded our | |
1187 | superclass's name. This in particular is bad if you change which classes | |
1188 | you inherit from, or add others. Fortunately, the pseudoclass \s-1SUPER\s0 | |
1189 | comes to the rescue here. | |
1190 | .PP | |
1191 | .Vb 1 | |
1192 | \& $self->SUPER::debug($Debugging); | |
1193 | .Ve | |
1194 | .PP | |
1195 | This way it starts looking in my class's \f(CW@ISA\fR. This only makes sense | |
1196 | from \fIwithin\fR a method call, though. Don't try to access anything | |
1197 | in \s-1SUPER::\s0 from anywhere else, because it doesn't exist outside | |
1198 | an overridden method call. Note that \f(CW\*(C`SUPER\*(C'\fR refers to the superclass of | |
1199 | the current package, \fInot\fR to the superclass of \f(CW$self\fR. | |
1200 | .PP | |
1201 | Things are getting a bit complicated here. Have we done anything | |
1202 | we shouldn't? As before, one way to test whether we're designing | |
1203 | a decent class is via the empty subclass test. Since we already have | |
1204 | an Employee class that we're trying to check, we'd better get a new | |
1205 | empty subclass that can derive from Employee. Here's one: | |
1206 | .PP | |
1207 | .Vb 3 | |
1208 | \& package Boss; | |
1209 | \& use Employee; # :-) | |
1210 | \& @ISA = qw(Employee); | |
1211 | .Ve | |
1212 | .PP | |
1213 | And here's the test program: | |
1214 | .PP | |
1215 | .Vb 4 | |
1216 | \& #!/usr/bin/perl -w | |
1217 | \& use strict; | |
1218 | \& use Boss; | |
1219 | \& Boss->debug(1); | |
1220 | .Ve | |
1221 | .PP | |
1222 | .Vb 1 | |
1223 | \& my $boss = Boss->new(); | |
1224 | .Ve | |
1225 | .PP | |
1226 | .Vb 4 | |
1227 | \& $boss->fullname->title("Don"); | |
1228 | \& $boss->fullname->surname("Pichon Alvarez"); | |
1229 | \& $boss->fullname->christian("Federico Jesus"); | |
1230 | \& $boss->fullname->nickname("Fred"); | |
1231 | .Ve | |
1232 | .PP | |
1233 | .Vb 2 | |
1234 | \& $boss->age(47); | |
1235 | \& $boss->peers("Frank", "Felipe", "Faust"); | |
1236 | .Ve | |
1237 | .PP | |
1238 | .Vb 2 | |
1239 | \& printf "%s is age %d.\en", $boss->fullname->as_string, $boss->age; | |
1240 | \& printf "His peers are: %s\en", join(", ", $boss->peers); | |
1241 | .Ve | |
1242 | .PP | |
1243 | Running it, we see that we're still ok. If you'd like to dump out your | |
1244 | object in a nice format, somewhat like the way the 'x' command works in | |
1245 | the debugger, you could use the Data::Dumper module from \s-1CPAN\s0 this way: | |
1246 | .PP | |
1247 | .Vb 3 | |
1248 | \& use Data::Dumper; | |
1249 | \& print "Here's the boss:\en"; | |
1250 | \& print Dumper($boss); | |
1251 | .Ve | |
1252 | .PP | |
1253 | Which shows us something like this: | |
1254 | .PP | |
1255 | .Vb 16 | |
1256 | \& Here's the boss: | |
1257 | \& $VAR1 = bless( { | |
1258 | \& _CENSUS => \e1, | |
1259 | \& FULLNAME => bless( { | |
1260 | \& TITLE => 'Don', | |
1261 | \& SURNAME => 'Pichon Alvarez', | |
1262 | \& NICK => 'Fred', | |
1263 | \& CHRISTIAN => 'Federico Jesus' | |
1264 | \& }, 'Fullname' ), | |
1265 | \& AGE => 47, | |
1266 | \& PEERS => [ | |
1267 | \& 'Frank', | |
1268 | \& 'Felipe', | |
1269 | \& 'Faust' | |
1270 | \& ] | |
1271 | \& }, 'Boss' ); | |
1272 | .Ve | |
1273 | .PP | |
1274 | Hm.... something's missing there. What about the salary, start date, | |
1275 | and \s-1ID\s0 fields? Well, we never set them to anything, even undef, so they | |
1276 | don't show up in the hash's keys. The Employee class has no \fInew()\fR method | |
1277 | of its own, and the \fInew()\fR method in Person doesn't know about Employees. | |
1278 | (Nor should it: proper \s-1OO\s0 design dictates that a subclass be allowed to | |
1279 | know about its immediate superclass, but never vice\-versa.) So let's | |
1280 | fix up \fIEmployee::new()\fR this way: | |
1281 | .PP | |
1282 | .Vb 9 | |
1283 | \& sub new { | |
1284 | \& my $class = shift; | |
1285 | \& my $self = $class->SUPER::new(); | |
1286 | \& $self->{SALARY} = undef; | |
1287 | \& $self->{ID} = undef; | |
1288 | \& $self->{START_DATE} = undef; | |
1289 | \& bless ($self, $class); # reconsecrate | |
1290 | \& return $self; | |
1291 | \& } | |
1292 | .Ve | |
1293 | .PP | |
1294 | Now if you dump out an Employee or Boss object, you'll find | |
1295 | that new fields show up there now. | |
1296 | .Sh "Multiple Inheritance" | |
1297 | .IX Subsection "Multiple Inheritance" | |
1298 | Ok, at the risk of confusing beginners and annoying \s-1OO\s0 gurus, it's | |
1299 | time to confess that Perl's object system includes that controversial | |
1300 | notion known as multiple inheritance, or \s-1MI\s0 for short. All this means | |
1301 | is that rather than having just one parent class who in turn might | |
1302 | itself have a parent class, etc., that you can directly inherit from | |
1303 | two or more parents. It's true that some uses of \s-1MI\s0 can get you into | |
1304 | trouble, although hopefully not quite so much trouble with Perl as with | |
1305 | dubiously-OO languages like \*(C+. | |
1306 | .PP | |
1307 | The way it works is actually pretty simple: just put more than one package | |
1308 | name in your \f(CW@ISA\fR array. When it comes time for Perl to go finding | |
1309 | methods for your object, it looks at each of these packages in order. | |
1310 | Well, kinda. It's actually a fully recursive, depth-first order. | |
1311 | Consider a bunch of \f(CW@ISA\fR arrays like this: | |
1312 | .PP | |
1313 | .Vb 3 | |
1314 | \& @First::ISA = qw( Alpha ); | |
1315 | \& @Second::ISA = qw( Beta ); | |
1316 | \& @Third::ISA = qw( First Second ); | |
1317 | .Ve | |
1318 | .PP | |
1319 | If you have an object of class Third: | |
1320 | .PP | |
1321 | .Vb 2 | |
1322 | \& my $ob = Third->new(); | |
1323 | \& $ob->spin(); | |
1324 | .Ve | |
1325 | .PP | |
1326 | How do we find a \fIspin()\fR method (or a \fInew()\fR method for that matter)? | |
1327 | Because the search is depth\-first, classes will be looked up | |
1328 | in the following order: Third, First, Alpha, Second, and Beta. | |
1329 | .PP | |
1330 | In practice, few class modules have been seen that actually | |
1331 | make use of \s-1MI\s0. One nearly always chooses simple containership of | |
1332 | one class within another over \s-1MI\s0. That's why our Person | |
1333 | object \fIcontained\fR a Fullname object. That doesn't mean | |
1334 | it \fIwas\fR one. | |
1335 | .PP | |
1336 | However, there is one particular area where \s-1MI\s0 in Perl is rampant: | |
1337 | borrowing another class's class methods. This is rather common, | |
1338 | especially with some bundled \*(L"objectless\*(R" classes, | |
1339 | like Exporter, DynaLoader, AutoLoader, and SelfLoader. These classes | |
1340 | do not provide constructors; they exist only so you may inherit their | |
1341 | class methods. (It's not entirely clear why inheritance was done | |
1342 | here rather than traditional module importation.) | |
1343 | .PP | |
1344 | For example, here is the \s-1POSIX\s0 module's \f(CW@ISA:\fR | |
1345 | .PP | |
1346 | .Vb 2 | |
1347 | \& package POSIX; | |
1348 | \& @ISA = qw(Exporter DynaLoader); | |
1349 | .Ve | |
1350 | .PP | |
1351 | The \s-1POSIX\s0 module isn't really an object module, but then, | |
1352 | neither are Exporter or DynaLoader. They're just lending their | |
1353 | classes' behaviours to \s-1POSIX\s0. | |
1354 | .PP | |
1355 | Why don't people use \s-1MI\s0 for object methods much? One reason is that | |
1356 | it can have complicated side\-effects. For one thing, your inheritance | |
1357 | graph (no longer a tree) might converge back to the same base class. | |
1358 | Although Perl guards against recursive inheritance, merely having parents | |
1359 | who are related to each other via a common ancestor, incestuous though | |
1360 | it sounds, is not forbidden. What if in our Third class shown above we | |
1361 | wanted its \fInew()\fR method to also call both overridden constructors in its | |
1362 | two parent classes? The \s-1SUPER\s0 notation would only find the first one. | |
1363 | Also, what about if the Alpha and Beta classes both had a common ancestor, | |
1364 | like Nought? If you kept climbing up the inheritance tree calling | |
1365 | overridden methods, you'd end up calling \fINought::new()\fR twice, | |
1366 | which might well be a bad idea. | |
1367 | .Sh "\s-1UNIVERSAL:\s0 The Root of All Objects" | |
1368 | .IX Subsection "UNIVERSAL: The Root of All Objects" | |
1369 | Wouldn't it be convenient if all objects were rooted at some ultimate | |
1370 | base class? That way you could give every object common methods without | |
1371 | having to go and add it to each and every \f(CW@ISA\fR. Well, it turns out that | |
1372 | you can. You don't see it, but Perl tacitly and irrevocably assumes | |
1373 | that there's an extra element at the end of \f(CW@ISA:\fR the class \s-1UNIVERSAL\s0. | |
1374 | In version 5.003, there were no predefined methods there, but you could put | |
1375 | whatever you felt like into it. | |
1376 | .PP | |
1377 | However, as of version 5.004 (or some subversive releases, like 5.003_08), | |
1378 | \&\s-1UNIVERSAL\s0 has some methods in it already. These are builtin to your Perl | |
1379 | binary, so they don't take any extra time to load. Predefined methods | |
1380 | include \fIisa()\fR, \fIcan()\fR, and \s-1\fIVERSION\s0()\fR. \fIisa()\fR tells you whether an object or | |
1381 | class \*(L"is\*(R" another one without having to traverse the hierarchy yourself: | |
1382 | .PP | |
1383 | .Vb 2 | |
1384 | \& $has_io = $fd->isa("IO::Handle"); | |
1385 | \& $itza_handle = IO::Socket->isa("IO::Handle"); | |
1386 | .Ve | |
1387 | .PP | |
1388 | The \fIcan()\fR method, called against that object or class, reports back | |
1389 | whether its string argument is a callable method name in that class. | |
1390 | In fact, it gives you back a function reference to that method: | |
1391 | .PP | |
1392 | .Vb 1 | |
1393 | \& $his_print_method = $obj->can('as_string'); | |
1394 | .Ve | |
1395 | .PP | |
1396 | Finally, the \s-1VERSION\s0 method checks whether the class (or the object's | |
1397 | class) has a package global called \f(CW$VERSION\fR that's high enough, as in: | |
1398 | .PP | |
1399 | .Vb 2 | |
1400 | \& Some_Module->VERSION(3.0); | |
1401 | \& $his_vers = $ob->VERSION(); | |
1402 | .Ve | |
1403 | .PP | |
1404 | However, we don't usually call \s-1VERSION\s0 ourselves. (Remember that an all | |
1405 | uppercase function name is a Perl convention that indicates that the | |
1406 | function will be automatically used by Perl in some way.) In this case, | |
1407 | it happens when you say | |
1408 | .PP | |
1409 | .Vb 1 | |
1410 | \& use Some_Module 3.0; | |
1411 | .Ve | |
1412 | .PP | |
1413 | If you wanted to add version checking to your Person class explained | |
1414 | above, just add this to Person.pm: | |
1415 | .PP | |
1416 | .Vb 1 | |
1417 | \& our $VERSION = '1.1'; | |
1418 | .Ve | |
1419 | .PP | |
1420 | and then in Employee.pm you can say | |
1421 | .PP | |
1422 | .Vb 1 | |
1423 | \& use Person 1.1; | |
1424 | .Ve | |
1425 | .PP | |
1426 | And it would make sure that you have at least that version number or | |
1427 | higher available. This is not the same as loading in that exact version | |
1428 | number. No mechanism currently exists for concurrent installation of | |
1429 | multiple versions of a module. Lamentably. | |
1430 | .SH "Alternate Object Representations" | |
1431 | .IX Header "Alternate Object Representations" | |
1432 | Nothing requires objects to be implemented as hash references. An object | |
1433 | can be any sort of reference so long as its referent has been suitably | |
1434 | blessed. That means scalar, array, and code references are also fair | |
1435 | game. | |
1436 | .PP | |
1437 | A scalar would work if the object has only one datum to hold. An array | |
1438 | would work for most cases, but makes inheritance a bit dodgy because | |
1439 | you have to invent new indices for the derived classes. | |
1440 | .Sh "Arrays as Objects" | |
1441 | .IX Subsection "Arrays as Objects" | |
1442 | If the user of your class honors the contract and sticks to the advertised | |
1443 | interface, then you can change its underlying interface if you feel | |
1444 | like it. Here's another implementation that conforms to the same | |
1445 | interface specification. This time we'll use an array reference | |
1446 | instead of a hash reference to represent the object. | |
1447 | .PP | |
1448 | .Vb 2 | |
1449 | \& package Person; | |
1450 | \& use strict; | |
1451 | .Ve | |
1452 | .PP | |
1453 | .Vb 1 | |
1454 | \& my($NAME, $AGE, $PEERS) = ( 0 .. 2 ); | |
1455 | .Ve | |
1456 | .PP | |
1457 | .Vb 11 | |
1458 | \& ############################################ | |
1459 | \& ## the object constructor (array version) ## | |
1460 | \& ############################################ | |
1461 | \& sub new { | |
1462 | \& my $self = []; | |
1463 | \& $self->[$NAME] = undef; # this is unnecessary | |
1464 | \& $self->[$AGE] = undef; # as is this | |
1465 | \& $self->[$PEERS] = []; # but this isn't, really | |
1466 | \& bless($self); | |
1467 | \& return $self; | |
1468 | \& } | |
1469 | .Ve | |
1470 | .PP | |
1471 | .Vb 5 | |
1472 | \& sub name { | |
1473 | \& my $self = shift; | |
1474 | \& if (@_) { $self->[$NAME] = shift } | |
1475 | \& return $self->[$NAME]; | |
1476 | \& } | |
1477 | .Ve | |
1478 | .PP | |
1479 | .Vb 5 | |
1480 | \& sub age { | |
1481 | \& my $self = shift; | |
1482 | \& if (@_) { $self->[$AGE] = shift } | |
1483 | \& return $self->[$AGE]; | |
1484 | \& } | |
1485 | .Ve | |
1486 | .PP | |
1487 | .Vb 5 | |
1488 | \& sub peers { | |
1489 | \& my $self = shift; | |
1490 | \& if (@_) { @{ $self->[$PEERS] } = @_ } | |
1491 | \& return @{ $self->[$PEERS] }; | |
1492 | \& } | |
1493 | .Ve | |
1494 | .PP | |
1495 | .Vb 1 | |
1496 | \& 1; # so the require or use succeeds | |
1497 | .Ve | |
1498 | .PP | |
1499 | You might guess that the array access would be a lot faster than the | |
1500 | hash access, but they're actually comparable. The array is a \fIlittle\fR | |
1501 | bit faster, but not more than ten or fifteen percent, even when you | |
1502 | replace the variables above like \f(CW$AGE\fR with literal numbers, like 1. | |
1503 | A bigger difference between the two approaches can be found in memory use. | |
1504 | A hash representation takes up more memory than an array representation | |
1505 | because you have to allocate memory for the keys as well as for the values. | |
1506 | However, it really isn't that bad, especially since as of version 5.004, | |
1507 | memory is only allocated once for a given hash key, no matter how many | |
1508 | hashes have that key. It's expected that sometime in the future, even | |
1509 | these differences will fade into obscurity as more efficient underlying | |
1510 | representations are devised. | |
1511 | .PP | |
1512 | Still, the tiny edge in speed (and somewhat larger one in memory) | |
1513 | is enough to make some programmers choose an array representation | |
1514 | for simple classes. There's still a little problem with | |
1515 | scalability, though, because later in life when you feel | |
1516 | like creating subclasses, you'll find that hashes just work | |
1517 | out better. | |
1518 | .Sh "Closures as Objects" | |
1519 | .IX Subsection "Closures as Objects" | |
1520 | Using a code reference to represent an object offers some fascinating | |
1521 | possibilities. We can create a new anonymous function (closure) who | |
1522 | alone in all the world can see the object's data. This is because we | |
1523 | put the data into an anonymous hash that's lexically visible only to | |
1524 | the closure we create, bless, and return as the object. This object's | |
1525 | methods turn around and call the closure as a regular subroutine call, | |
1526 | passing it the field we want to affect. (Yes, | |
1527 | the double-function call is slow, but if you wanted fast, you wouldn't | |
1528 | be using objects at all, eh? :\-) | |
1529 | .PP | |
1530 | Use would be similar to before: | |
1531 | .PP | |
1532 | .Vb 7 | |
1533 | \& use Person; | |
1534 | \& $him = Person->new(); | |
1535 | \& $him->name("Jason"); | |
1536 | \& $him->age(23); | |
1537 | \& $him->peers( [ "Norbert", "Rhys", "Phineas" ] ); | |
1538 | \& printf "%s is %d years old.\en", $him->name, $him->age; | |
1539 | \& print "His peers are: ", join(", ", @{$him->peers}), "\en"; | |
1540 | .Ve | |
1541 | .PP | |
1542 | but the implementation would be radically, perhaps even sublimely | |
1543 | different: | |
1544 | .PP | |
1545 | .Vb 1 | |
1546 | \& package Person; | |
1547 | .Ve | |
1548 | .PP | |
1549 | .Vb 15 | |
1550 | \& sub new { | |
1551 | \& my $class = shift; | |
1552 | \& my $self = { | |
1553 | \& NAME => undef, | |
1554 | \& AGE => undef, | |
1555 | \& PEERS => [], | |
1556 | \& }; | |
1557 | \& my $closure = sub { | |
1558 | \& my $field = shift; | |
1559 | \& if (@_) { $self->{$field} = shift } | |
1560 | \& return $self->{$field}; | |
1561 | \& }; | |
1562 | \& bless($closure, $class); | |
1563 | \& return $closure; | |
1564 | \& } | |
1565 | .Ve | |
1566 | .PP | |
1567 | .Vb 3 | |
1568 | \& sub name { &{ $_[0] }("NAME", @_[ 1 .. $#_ ] ) } | |
1569 | \& sub age { &{ $_[0] }("AGE", @_[ 1 .. $#_ ] ) } | |
1570 | \& sub peers { &{ $_[0] }("PEERS", @_[ 1 .. $#_ ] ) } | |
1571 | .Ve | |
1572 | .PP | |
1573 | .Vb 1 | |
1574 | \& 1; | |
1575 | .Ve | |
1576 | .PP | |
1577 | Because this object is hidden behind a code reference, it's probably a bit | |
1578 | mysterious to those whose background is more firmly rooted in standard | |
1579 | procedural or object-based programming languages than in functional | |
1580 | programming languages whence closures derive. The object | |
1581 | created and returned by the \fInew()\fR method is itself not a data reference | |
1582 | as we've seen before. It's an anonymous code reference that has within | |
1583 | it access to a specific version (lexical binding and instantiation) | |
1584 | of the object's data, which are stored in the private variable \f(CW$self\fR. | |
1585 | Although this is the same function each time, it contains a different | |
1586 | version of \f(CW$self\fR. | |
1587 | .PP | |
1588 | When a method like \f(CW\*(C`$him\->name("Jason")\*(C'\fR is called, its implicit | |
1589 | zeroth argument is the invoking object\*(--just as it is with all method | |
1590 | calls. But in this case, it's our code reference (something like a | |
1591 | function pointer in \*(C+, but with deep binding of lexical variables). | |
1592 | There's not a lot to be done with a code reference beyond calling it, so | |
1593 | that's just what we do when we say \f(CW\*(C`&{$_[0]}\*(C'\fR. This is just a regular | |
1594 | function call, not a method call. The initial argument is the string | |
1595 | \&\*(L"\s-1NAME\s0\*(R", and any remaining arguments are whatever had been passed to the | |
1596 | method itself. | |
1597 | .PP | |
1598 | Once we're executing inside the closure that had been created in \fInew()\fR, | |
1599 | the \f(CW$self\fR hash reference suddenly becomes visible. The closure grabs | |
1600 | its first argument (\*(L"\s-1NAME\s0\*(R" in this case because that's what the \fIname()\fR | |
1601 | method passed it), and uses that string to subscript into the private | |
1602 | hash hidden in its unique version of \f(CW$self\fR. | |
1603 | .PP | |
1604 | Nothing under the sun will allow anyone outside the executing method to | |
1605 | be able to get at this hidden data. Well, nearly nothing. You \fIcould\fR | |
1606 | single step through the program using the debugger and find out the | |
1607 | pieces while you're in the method, but everyone else is out of luck. | |
1608 | .PP | |
1609 | There, if that doesn't excite the Scheme folks, then I just don't know | |
1610 | what will. Translation of this technique into \*(C+, Java, or any other | |
1611 | braindead-static language is left as a futile exercise for aficionados | |
1612 | of those camps. | |
1613 | .PP | |
1614 | You could even add a bit of nosiness via the \fIcaller()\fR function and | |
1615 | make the closure refuse to operate unless called via its own package. | |
1616 | This would no doubt satisfy certain fastidious concerns of programming | |
1617 | police and related puritans. | |
1618 | .PP | |
1619 | If you were wondering when Hubris, the third principle virtue of a | |
1620 | programmer, would come into play, here you have it. (More seriously, | |
1621 | Hubris is just the pride in craftsmanship that comes from having written | |
1622 | a sound bit of well-designed code.) | |
1623 | .SH "AUTOLOAD: Proxy Methods" | |
1624 | .IX Header "AUTOLOAD: Proxy Methods" | |
1625 | Autoloading is a way to intercept calls to undefined methods. An autoload | |
1626 | routine may choose to create a new function on the fly, either loaded | |
1627 | from disk or perhaps just \fIeval()\fRed right there. This define-on-the-fly | |
1628 | strategy is why it's called autoloading. | |
1629 | .PP | |
1630 | But that's only one possible approach. Another one is to just | |
1631 | have the autoloaded method itself directly provide the | |
1632 | requested service. When used in this way, you may think | |
1633 | of autoloaded methods as \*(L"proxy\*(R" methods. | |
1634 | .PP | |
1635 | When Perl tries to call an undefined function in a particular package | |
1636 | and that function is not defined, it looks for a function in | |
1637 | that same package called \s-1AUTOLOAD\s0. If one exists, it's called | |
1638 | with the same arguments as the original function would have had. | |
1639 | The fully-qualified name of the function is stored in that package's | |
1640 | global variable \f(CW$AUTOLOAD\fR. Once called, the function can do anything | |
1641 | it would like, including defining a new function by the right name, and | |
1642 | then doing a really fancy kind of \f(CW\*(C`goto\*(C'\fR right to it, erasing itself | |
1643 | from the call stack. | |
1644 | .PP | |
1645 | What does this have to do with objects? After all, we keep talking about | |
1646 | functions, not methods. Well, since a method is just a function with | |
1647 | an extra argument and some fancier semantics about where it's found, | |
1648 | we can use autoloading for methods, too. Perl doesn't start looking | |
1649 | for an \s-1AUTOLOAD\s0 method until it has exhausted the recursive hunt up | |
1650 | through \f(CW@ISA\fR, though. Some programmers have even been known to define | |
1651 | a \s-1UNIVERSAL::AUTOLOAD\s0 method to trap unresolved method calls to any | |
1652 | kind of object. | |
1653 | .Sh "Autoloaded Data Methods" | |
1654 | .IX Subsection "Autoloaded Data Methods" | |
1655 | You probably began to get a little suspicious about the duplicated | |
1656 | code way back earlier when we first showed you the Person class, and | |
1657 | then later the Employee class. Each method used to access the | |
1658 | hash fields looked virtually identical. This should have tickled | |
1659 | that great programming virtue, Impatience, but for the time, | |
1660 | we let Laziness win out, and so did nothing. Proxy methods can cure | |
1661 | this. | |
1662 | .PP | |
1663 | Instead of writing a new function every time we want a new data field, | |
1664 | we'll use the autoload mechanism to generate (actually, mimic) methods on | |
1665 | the fly. To verify that we're accessing a valid member, we will check | |
1666 | against an \f(CW\*(C`_permitted\*(C'\fR (pronounced \*(L"under\-permitted\*(R") field, which | |
1667 | is a reference to a file-scoped lexical (like a C file static) hash of permitted fields in this record | |
1668 | called \f(CW%fields\fR. Why the underscore? For the same reason as the _CENSUS | |
1669 | field we once used: as a marker that means \*(L"for internal use only\*(R". | |
1670 | .PP | |
1671 | Here's what the module initialization code and class | |
1672 | constructor will look like when taking this approach: | |
1673 | .PP | |
1674 | .Vb 3 | |
1675 | \& package Person; | |
1676 | \& use Carp; | |
1677 | \& our $AUTOLOAD; # it's a package global | |
1678 | .Ve | |
1679 | .PP | |
1680 | .Vb 5 | |
1681 | \& my %fields = ( | |
1682 | \& name => undef, | |
1683 | \& age => undef, | |
1684 | \& peers => undef, | |
1685 | \& ); | |
1686 | .Ve | |
1687 | .PP | |
1688 | .Vb 9 | |
1689 | \& sub new { | |
1690 | \& my $class = shift; | |
1691 | \& my $self = { | |
1692 | \& _permitted => \e%fields, | |
1693 | \& %fields, | |
1694 | \& }; | |
1695 | \& bless $self, $class; | |
1696 | \& return $self; | |
1697 | \& } | |
1698 | .Ve | |
1699 | .PP | |
1700 | If we wanted our record to have default values, we could fill those in | |
1701 | where current we have \f(CW\*(C`undef\*(C'\fR in the \f(CW%fields\fR hash. | |
1702 | .PP | |
1703 | Notice how we saved a reference to our class data on the object itself? | |
1704 | Remember that it's important to access class data through the object | |
1705 | itself instead of having any method reference \f(CW%fields\fR directly, or else | |
1706 | you won't have a decent inheritance. | |
1707 | .PP | |
1708 | The real magic, though, is going to reside in our proxy method, which | |
1709 | will handle all calls to undefined methods for objects of class Person | |
1710 | (or subclasses of Person). It has to be called \s-1AUTOLOAD\s0. Again, it's | |
1711 | all caps because it's called for us implicitly by Perl itself, not by | |
1712 | a user directly. | |
1713 | .PP | |
1714 | .Vb 4 | |
1715 | \& sub AUTOLOAD { | |
1716 | \& my $self = shift; | |
1717 | \& my $type = ref($self) | |
1718 | \& or croak "$self is not an object"; | |
1719 | .Ve | |
1720 | .PP | |
1721 | .Vb 2 | |
1722 | \& my $name = $AUTOLOAD; | |
1723 | \& $name =~ s/.*://; # strip fully-qualified portion | |
1724 | .Ve | |
1725 | .PP | |
1726 | .Vb 3 | |
1727 | \& unless (exists $self->{_permitted}->{$name} ) { | |
1728 | \& croak "Can't access `$name' field in class $type"; | |
1729 | \& } | |
1730 | .Ve | |
1731 | .PP | |
1732 | .Vb 6 | |
1733 | \& if (@_) { | |
1734 | \& return $self->{$name} = shift; | |
1735 | \& } else { | |
1736 | \& return $self->{$name}; | |
1737 | \& } | |
1738 | \& } | |
1739 | .Ve | |
1740 | .PP | |
1741 | Pretty nifty, eh? All we have to do to add new data fields | |
1742 | is modify \f(CW%fields\fR. No new functions need be written. | |
1743 | .PP | |
1744 | I could have avoided the \f(CW\*(C`_permitted\*(C'\fR field entirely, but I | |
1745 | wanted to demonstrate how to store a reference to class data on the | |
1746 | object so you wouldn't have to access that class data | |
1747 | directly from an object method. | |
1748 | .Sh "Inherited Autoloaded Data Methods" | |
1749 | .IX Subsection "Inherited Autoloaded Data Methods" | |
1750 | But what about inheritance? Can we define our Employee | |
1751 | class similarly? Yes, so long as we're careful enough. | |
1752 | .PP | |
1753 | Here's how to be careful: | |
1754 | .PP | |
1755 | .Vb 4 | |
1756 | \& package Employee; | |
1757 | \& use Person; | |
1758 | \& use strict; | |
1759 | \& our @ISA = qw(Person); | |
1760 | .Ve | |
1761 | .PP | |
1762 | .Vb 4 | |
1763 | \& my %fields = ( | |
1764 | \& id => undef, | |
1765 | \& salary => undef, | |
1766 | \& ); | |
1767 | .Ve | |
1768 | .PP | |
1769 | .Vb 10 | |
1770 | \& sub new { | |
1771 | \& my $class = shift; | |
1772 | \& my $self = $class->SUPER::new(); | |
1773 | \& my($element); | |
1774 | \& foreach $element (keys %fields) { | |
1775 | \& $self->{_permitted}->{$element} = $fields{$element}; | |
1776 | \& } | |
1777 | \& @{$self}{keys %fields} = values %fields; | |
1778 | \& return $self; | |
1779 | \& } | |
1780 | .Ve | |
1781 | .PP | |
1782 | Once we've done this, we don't even need to have an | |
1783 | \&\s-1AUTOLOAD\s0 function in the Employee package, because | |
1784 | we'll grab Person's version of that via inheritance, | |
1785 | and it will all work out just fine. | |
1786 | .SH "Metaclassical Tools" | |
1787 | .IX Header "Metaclassical Tools" | |
1788 | Even though proxy methods can provide a more convenient approach to making | |
1789 | more struct-like classes than tediously coding up data methods as | |
1790 | functions, it still leaves a bit to be desired. For one thing, it means | |
1791 | you have to handle bogus calls that you don't mean to trap via your proxy. | |
1792 | It also means you have to be quite careful when dealing with inheritance, | |
1793 | as detailed above. | |
1794 | .PP | |
1795 | Perl programmers have responded to this by creating several different | |
1796 | class construction classes. These metaclasses are classes | |
1797 | that create other classes. A couple worth looking at are | |
1798 | Class::Struct and Alias. These and other related metaclasses can be | |
1799 | found in the modules directory on \s-1CPAN\s0. | |
1800 | .Sh "Class::Struct" | |
1801 | .IX Subsection "Class::Struct" | |
1802 | One of the older ones is Class::Struct. In fact, its syntax and | |
1803 | interface were sketched out long before perl5 even solidified into a | |
1804 | real thing. What it does is provide you a way to \*(L"declare\*(R" a class | |
1805 | as having objects whose fields are of a specific type. The function | |
1806 | that does this is called, not surprisingly enough, \fIstruct()\fR. Because | |
1807 | structures or records are not base types in Perl, each time you want to | |
1808 | create a class to provide a record-like data object, you yourself have | |
1809 | to define a \fInew()\fR method, plus separate data-access methods for each of | |
1810 | that record's fields. You'll quickly become bored with this process. | |
1811 | The \fIClass::Struct::struct()\fR function alleviates this tedium. | |
1812 | .PP | |
1813 | Here's a simple example of using it: | |
1814 | .PP | |
1815 | .Vb 2 | |
1816 | \& use Class::Struct qw(struct); | |
1817 | \& use Jobbie; # user-defined; see below | |
1818 | .Ve | |
1819 | .PP | |
1820 | .Vb 5 | |
1821 | \& struct 'Fred' => { | |
1822 | \& one => '$', | |
1823 | \& many => '@', | |
1824 | \& profession => 'Jobbie', # does not call Jobbie->new() | |
1825 | \& }; | |
1826 | .Ve | |
1827 | .PP | |
1828 | .Vb 2 | |
1829 | \& $ob = Fred->new(profession => Jobbie->new()); | |
1830 | \& $ob->one("hmmmm"); | |
1831 | .Ve | |
1832 | .PP | |
1833 | .Vb 4 | |
1834 | \& $ob->many(0, "here"); | |
1835 | \& $ob->many(1, "you"); | |
1836 | \& $ob->many(2, "go"); | |
1837 | \& print "Just set: ", $ob->many(2), "\en"; | |
1838 | .Ve | |
1839 | .PP | |
1840 | .Vb 1 | |
1841 | \& $ob->profession->salary(10_000); | |
1842 | .Ve | |
1843 | .PP | |
1844 | You can declare types in the struct to be basic Perl types, or | |
1845 | user-defined types (classes). User types will be initialized by calling | |
1846 | that class's \fInew()\fR method. | |
1847 | .PP | |
1848 | Take care that the \f(CW\*(C`Jobbie\*(C'\fR object is not created automatically by the | |
1849 | \&\f(CW\*(C`Fred\*(C'\fR class's \fInew()\fR method, so you should specify a \f(CW\*(C`Jobbie\*(C'\fR object | |
1850 | when you create an instance of \f(CW\*(C`Fred\*(C'\fR. | |
1851 | .PP | |
1852 | Here's a real-world example of using struct generation. Let's say you | |
1853 | wanted to override Perl's idea of \fIgethostbyname()\fR and \fIgethostbyaddr()\fR so | |
1854 | that they would return objects that acted like C structures. We don't | |
1855 | care about high\-falutin' \s-1OO\s0 gunk. All we want is for these objects to | |
1856 | act like structs in the C sense. | |
1857 | .PP | |
1858 | .Vb 5 | |
1859 | \& use Socket; | |
1860 | \& use Net::hostent; | |
1861 | \& $h = gethostbyname("perl.com"); # object return | |
1862 | \& printf "perl.com's real name is %s, address %s\en", | |
1863 | \& $h->name, inet_ntoa($h->addr); | |
1864 | .Ve | |
1865 | .PP | |
1866 | Here's how to do this using the Class::Struct module. | |
1867 | The crux is going to be this call: | |
1868 | .PP | |
1869 | .Vb 7 | |
1870 | \& struct 'Net::hostent' => [ # note bracket | |
1871 | \& name => '$', | |
1872 | \& aliases => '@', | |
1873 | \& addrtype => '$', | |
1874 | \& 'length' => '$', | |
1875 | \& addr_list => '@', | |
1876 | \& ]; | |
1877 | .Ve | |
1878 | .PP | |
1879 | Which creates object methods of those names and types. | |
1880 | It even creates a \fInew()\fR method for us. | |
1881 | .PP | |
1882 | We could also have implemented our object this way: | |
1883 | .PP | |
1884 | .Vb 7 | |
1885 | \& struct 'Net::hostent' => { # note brace | |
1886 | \& name => '$', | |
1887 | \& aliases => '@', | |
1888 | \& addrtype => '$', | |
1889 | \& 'length' => '$', | |
1890 | \& addr_list => '@', | |
1891 | \& }; | |
1892 | .Ve | |
1893 | .PP | |
1894 | and then Class::Struct would have used an anonymous hash as the object | |
1895 | type, instead of an anonymous array. The array is faster and smaller, | |
1896 | but the hash works out better if you eventually want to do inheritance. | |
1897 | Since for this struct-like object we aren't planning on inheritance, | |
1898 | this time we'll opt for better speed and size over better flexibility. | |
1899 | .PP | |
1900 | Here's the whole implementation: | |
1901 | .PP | |
1902 | .Vb 2 | |
1903 | \& package Net::hostent; | |
1904 | \& use strict; | |
1905 | .Ve | |
1906 | .PP | |
1907 | .Vb 11 | |
1908 | \& BEGIN { | |
1909 | \& use Exporter (); | |
1910 | \& our @EXPORT = qw(gethostbyname gethostbyaddr gethost); | |
1911 | \& our @EXPORT_OK = qw( | |
1912 | \& $h_name @h_aliases | |
1913 | \& $h_addrtype $h_length | |
1914 | \& @h_addr_list $h_addr | |
1915 | \& ); | |
1916 | \& our %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] ); | |
1917 | \& } | |
1918 | \& our @EXPORT_OK; | |
1919 | .Ve | |
1920 | .PP | |
1921 | .Vb 2 | |
1922 | \& # Class::Struct forbids use of @ISA | |
1923 | \& sub import { goto &Exporter::import } | |
1924 | .Ve | |
1925 | .PP | |
1926 | .Vb 8 | |
1927 | \& use Class::Struct qw(struct); | |
1928 | \& struct 'Net::hostent' => [ | |
1929 | \& name => '$', | |
1930 | \& aliases => '@', | |
1931 | \& addrtype => '$', | |
1932 | \& 'length' => '$', | |
1933 | \& addr_list => '@', | |
1934 | \& ]; | |
1935 | .Ve | |
1936 | .PP | |
1937 | .Vb 1 | |
1938 | \& sub addr { shift->addr_list->[0] } | |
1939 | .Ve | |
1940 | .PP | |
1941 | .Vb 11 | |
1942 | \& sub populate (@) { | |
1943 | \& return unless @_; | |
1944 | \& my $hob = new(); # Class::Struct made this! | |
1945 | \& $h_name = $hob->[0] = $_[0]; | |
1946 | \& @h_aliases = @{ $hob->[1] } = split ' ', $_[1]; | |
1947 | \& $h_addrtype = $hob->[2] = $_[2]; | |
1948 | \& $h_length = $hob->[3] = $_[3]; | |
1949 | \& $h_addr = $_[4]; | |
1950 | \& @h_addr_list = @{ $hob->[4] } = @_[ (4 .. $#_) ]; | |
1951 | \& return $hob; | |
1952 | \& } | |
1953 | .Ve | |
1954 | .PP | |
1955 | .Vb 1 | |
1956 | \& sub gethostbyname ($) { populate(CORE::gethostbyname(shift)) } | |
1957 | .Ve | |
1958 | .PP | |
1959 | .Vb 7 | |
1960 | \& sub gethostbyaddr ($;$) { | |
1961 | \& my ($addr, $addrtype); | |
1962 | \& $addr = shift; | |
1963 | \& require Socket unless @_; | |
1964 | \& $addrtype = @_ ? shift : Socket::AF_INET(); | |
1965 | \& populate(CORE::gethostbyaddr($addr, $addrtype)) | |
1966 | \& } | |
1967 | .Ve | |
1968 | .PP | |
1969 | .Vb 8 | |
1970 | \& sub gethost($) { | |
1971 | \& if ($_[0] =~ /^\ed+(?:\e.\ed+(?:\e.\ed+(?:\e.\ed+)?)?)?$/) { | |
1972 | \& require Socket; | |
1973 | \& &gethostbyaddr(Socket::inet_aton(shift)); | |
1974 | \& } else { | |
1975 | \& &gethostbyname; | |
1976 | \& } | |
1977 | \& } | |
1978 | .Ve | |
1979 | .PP | |
1980 | .Vb 1 | |
1981 | \& 1; | |
1982 | .Ve | |
1983 | .PP | |
1984 | We've snuck in quite a fair bit of other concepts besides just dynamic | |
1985 | class creation, like overriding core functions, import/export bits, | |
1986 | function prototyping, short-cut function call via \f(CW&whatever\fR, and | |
1987 | function replacement with \f(CW\*(C`goto &whatever\*(C'\fR. These all mostly make | |
1988 | sense from the perspective of a traditional module, but as you can see, | |
1989 | we can also use them in an object module. | |
1990 | .PP | |
1991 | You can look at other object\-based, struct-like overrides of core | |
1992 | functions in the 5.004 release of Perl in File::stat, Net::hostent, | |
1993 | Net::netent, Net::protoent, Net::servent, Time::gmtime, Time::localtime, | |
1994 | User::grent, and User::pwent. These modules have a final component | |
1995 | that's all lowercase, by convention reserved for compiler pragmas, | |
1996 | because they affect the compilation and change a builtin function. | |
1997 | They also have the type names that a C programmer would most expect. | |
1998 | .Sh "Data Members as Variables" | |
1999 | .IX Subsection "Data Members as Variables" | |
2000 | If you're used to \*(C+ objects, then you're accustomed to being able to | |
2001 | get at an object's data members as simple variables from within a method. | |
2002 | The Alias module provides for this, as well as a good bit more, such | |
2003 | as the possibility of private methods that the object can call but folks | |
2004 | outside the class cannot. | |
2005 | .PP | |
2006 | Here's an example of creating a Person using the Alias module. | |
2007 | When you update these magical instance variables, you automatically | |
2008 | update value fields in the hash. Convenient, eh? | |
2009 | .PP | |
2010 | .Vb 1 | |
2011 | \& package Person; | |
2012 | .Ve | |
2013 | .PP | |
2014 | .Vb 11 | |
2015 | \& # this is the same as before... | |
2016 | \& sub new { | |
2017 | \& my $class = shift; | |
2018 | \& my $self = { | |
2019 | \& NAME => undef, | |
2020 | \& AGE => undef, | |
2021 | \& PEERS => [], | |
2022 | \& }; | |
2023 | \& bless($self, $class); | |
2024 | \& return $self; | |
2025 | \& } | |
2026 | .Ve | |
2027 | .PP | |
2028 | .Vb 2 | |
2029 | \& use Alias qw(attr); | |
2030 | \& our ($NAME, $AGE, $PEERS); | |
2031 | .Ve | |
2032 | .PP | |
2033 | .Vb 5 | |
2034 | \& sub name { | |
2035 | \& my $self = attr shift; | |
2036 | \& if (@_) { $NAME = shift; } | |
2037 | \& return $NAME; | |
2038 | \& } | |
2039 | .Ve | |
2040 | .PP | |
2041 | .Vb 5 | |
2042 | \& sub age { | |
2043 | \& my $self = attr shift; | |
2044 | \& if (@_) { $AGE = shift; } | |
2045 | \& return $AGE; | |
2046 | \& } | |
2047 | .Ve | |
2048 | .PP | |
2049 | .Vb 5 | |
2050 | \& sub peers { | |
2051 | \& my $self = attr shift; | |
2052 | \& if (@_) { @PEERS = @_; } | |
2053 | \& return @PEERS; | |
2054 | \& } | |
2055 | .Ve | |
2056 | .PP | |
2057 | .Vb 5 | |
2058 | \& sub exclaim { | |
2059 | \& my $self = attr shift; | |
2060 | \& return sprintf "Hi, I'm %s, age %d, working with %s", | |
2061 | \& $NAME, $AGE, join(", ", @PEERS); | |
2062 | \& } | |
2063 | .Ve | |
2064 | .PP | |
2065 | .Vb 4 | |
2066 | \& sub happy_birthday { | |
2067 | \& my $self = attr shift; | |
2068 | \& return ++$AGE; | |
2069 | \& } | |
2070 | .Ve | |
2071 | .PP | |
2072 | The need for the \f(CW\*(C`our\*(C'\fR declaration is because what Alias does | |
2073 | is play with package globals with the same name as the fields. To use | |
2074 | globals while \f(CW\*(C`use strict\*(C'\fR is in effect, you have to predeclare them. | |
2075 | These package variables are localized to the block enclosing the \fIattr()\fR | |
2076 | call just as if you'd used a \fIlocal()\fR on them. However, that means that | |
2077 | they're still considered global variables with temporary values, just | |
2078 | as with any other \fIlocal()\fR. | |
2079 | .PP | |
2080 | It would be nice to combine Alias with | |
2081 | something like Class::Struct or Class::MethodMaker. | |
2082 | .SH "NOTES" | |
2083 | .IX Header "NOTES" | |
2084 | .Sh "Object Terminology" | |
2085 | .IX Subsection "Object Terminology" | |
2086 | In the various \s-1OO\s0 literature, it seems that a lot of different words | |
2087 | are used to describe only a few different concepts. If you're not | |
2088 | already an object programmer, then you don't need to worry about all | |
2089 | these fancy words. But if you are, then you might like to know how to | |
2090 | get at the same concepts in Perl. | |
2091 | .PP | |
2092 | For example, it's common to call an object an \fIinstance\fR of a class | |
2093 | and to call those objects' methods \fIinstance methods\fR. Data fields | |
2094 | peculiar to each object are often called \fIinstance data\fR or \fIobject | |
2095 | attributes\fR, and data fields common to all members of that class are | |
2096 | \&\fIclass data\fR, \fIclass attributes\fR, or \fIstatic data members\fR. | |
2097 | .PP | |
2098 | Also, \fIbase class\fR, \fIgeneric class\fR, and \fIsuperclass\fR all describe | |
2099 | the same notion, whereas \fIderived class\fR, \fIspecific class\fR, and | |
2100 | \&\fIsubclass\fR describe the other related one. | |
2101 | .PP | |
2102 | \&\*(C+ programmers have \fIstatic methods\fR and \fIvirtual methods\fR, | |
2103 | but Perl only has \fIclass methods\fR and \fIobject methods\fR. | |
2104 | Actually, Perl only has methods. Whether a method gets used | |
2105 | as a class or object method is by usage only. You could accidentally | |
2106 | call a class method (one expecting a string argument) on an | |
2107 | object (one expecting a reference), or vice versa. | |
2108 | .PP | |
2109 | From the \*(C+ perspective, all methods in Perl are virtual. | |
2110 | This, by the way, is why they are never checked for function | |
2111 | prototypes in the argument list as regular builtin and user-defined | |
2112 | functions can be. | |
2113 | .PP | |
2114 | Because a class is itself something of an object, Perl's classes can be | |
2115 | taken as describing both a \*(L"class as meta\-object\*(R" (also called \fIobject | |
2116 | factory\fR) philosophy and the \*(L"class as type definition\*(R" (\fIdeclaring\fR | |
2117 | behaviour, not \fIdefining\fR mechanism) idea. \*(C+ supports the latter | |
2118 | notion, but not the former. | |
2119 | .SH "SEE ALSO" | |
2120 | .IX Header "SEE ALSO" | |
2121 | The following manpages will doubtless provide more | |
2122 | background for this one: | |
2123 | perlmod, | |
2124 | perlref, | |
2125 | perlobj, | |
2126 | perlbot, | |
2127 | perltie, | |
2128 | and | |
2129 | overload. | |
2130 | .PP | |
2131 | perlboot is a kinder, gentler introduction to object-oriented | |
2132 | programming. | |
2133 | .PP | |
2134 | perltooc provides more detail on class data. | |
2135 | .PP | |
2136 | Some modules which might prove interesting are Class::Accessor, | |
2137 | Class::Class, Class::Contract, Class::Data::Inheritable, | |
2138 | Class::MethodMaker and Tie::SecureHash | |
2139 | .SH "AUTHOR AND COPYRIGHT" | |
2140 | .IX Header "AUTHOR AND COPYRIGHT" | |
2141 | Copyright (c) 1997, 1998 Tom Christiansen | |
2142 | All rights reserved. | |
2143 | .PP | |
2144 | This documentation is free; you can redistribute it and/or modify it | |
2145 | under the same terms as Perl itself. | |
2146 | .PP | |
2147 | Irrespective of its distribution, all code examples in this file | |
2148 | are hereby placed into the public domain. You are permitted and | |
2149 | encouraged to use this code in your own programs for fun | |
2150 | or for profit as you see fit. A simple comment in the code giving | |
2151 | credit would be courteous but is not required. | |
2152 | .SH "COPYRIGHT" | |
2153 | .IX Header "COPYRIGHT" | |
2154 | .Sh "Acknowledgments" | |
2155 | .IX Subsection "Acknowledgments" | |
2156 | Thanks to | |
2157 | Larry Wall, | |
2158 | Roderick Schertler, | |
2159 | Gurusamy Sarathy, | |
2160 | Dean Roehrich, | |
2161 | Raphael Manfredi, | |
2162 | Brent Halsey, | |
2163 | Greg Bacon, | |
2164 | Brad Appleton, | |
2165 | and many others for their helpful comments. |