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