Commit | Line | Data |
---|---|---|
920dae64 AT |
1 | .\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32 |
2 | .\" | |
3 | .\" Standard preamble: | |
4 | .\" ======================================================================== | |
5 | .de Sh \" Subsection heading | |
6 | .br | |
7 | .if t .Sp | |
8 | .ne 5 | |
9 | .PP | |
10 | \fB\\$1\fR | |
11 | .PP | |
12 | .. | |
13 | .de Sp \" Vertical space (when we can't use .PP) | |
14 | .if t .sp .5v | |
15 | .if n .sp | |
16 | .. | |
17 | .de Vb \" Begin verbatim text | |
18 | .ft CW | |
19 | .nf | |
20 | .ne \\$1 | |
21 | .. | |
22 | .de Ve \" End verbatim text | |
23 | .ft R | |
24 | .fi | |
25 | .. | |
26 | .\" Set up some character translations and predefined strings. \*(-- will | |
27 | .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left | |
28 | .\" double quote, and \*(R" will give a right double quote. | will give a | |
29 | .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to | |
30 | .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' | |
31 | .\" expand to `' in nroff, nothing in troff, for use with C<>. | |
32 | .tr \(*W-|\(bv\*(Tr | |
33 | .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' | |
34 | .ie n \{\ | |
35 | . ds -- \(*W- | |
36 | . ds PI pi | |
37 | . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch | |
38 | . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch | |
39 | . ds L" "" | |
40 | . ds R" "" | |
41 | . ds C` "" | |
42 | . ds C' "" | |
43 | 'br\} | |
44 | .el\{\ | |
45 | . ds -- \|\(em\| | |
46 | . ds PI \(*p | |
47 | . ds L" `` | |
48 | . ds R" '' | |
49 | 'br\} | |
50 | .\" | |
51 | .\" If the F register is turned on, we'll generate index entries on stderr for | |
52 | .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index | |
53 | .\" entries marked with X<> in POD. Of course, you'll have to process the | |
54 | .\" output yourself in some meaningful fashion. | |
55 | .if \nF \{\ | |
56 | . de IX | |
57 | . tm Index:\\$1\t\\n%\t"\\$2" | |
58 | .. | |
59 | . nr % 0 | |
60 | . rr F | |
61 | .\} | |
62 | .\" | |
63 | .\" For nroff, turn off justification. Always turn off hyphenation; it makes | |
64 | .\" way too many mistakes in technical documents. | |
65 | .hy 0 | |
66 | .if n .na | |
67 | .\" | |
68 | .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). | |
69 | .\" Fear. Run. Save yourself. No user-serviceable parts. | |
70 | . \" fudge factors for nroff and troff | |
71 | .if n \{\ | |
72 | . ds #H 0 | |
73 | . ds #V .8m | |
74 | . ds #F .3m | |
75 | . ds #[ \f1 | |
76 | . ds #] \fP | |
77 | .\} | |
78 | .if t \{\ | |
79 | . ds #H ((1u-(\\\\n(.fu%2u))*.13m) | |
80 | . ds #V .6m | |
81 | . ds #F 0 | |
82 | . ds #[ \& | |
83 | . ds #] \& | |
84 | .\} | |
85 | . \" simple accents for nroff and troff | |
86 | .if n \{\ | |
87 | . ds ' \& | |
88 | . ds ` \& | |
89 | . ds ^ \& | |
90 | . ds , \& | |
91 | . ds ~ ~ | |
92 | . ds / | |
93 | .\} | |
94 | .if t \{\ | |
95 | . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" | |
96 | . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' | |
97 | . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' | |
98 | . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' | |
99 | . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' | |
100 | . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' | |
101 | .\} | |
102 | . \" troff and (daisy-wheel) nroff accents | |
103 | .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' | |
104 | .ds 8 \h'\*(#H'\(*b\h'-\*(#H' | |
105 | .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] | |
106 | .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' | |
107 | .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' | |
108 | .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] | |
109 | .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] | |
110 | .ds ae a\h'-(\w'a'u*4/10)'e | |
111 | .ds Ae A\h'-(\w'A'u*4/10)'E | |
112 | . \" corrections for vroff | |
113 | .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' | |
114 | .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' | |
115 | . \" for low resolution devices (crt and lpr) | |
116 | .if \n(.H>23 .if \n(.V>19 \ | |
117 | \{\ | |
118 | . ds : e | |
119 | . ds 8 ss | |
120 | . ds o a | |
121 | . ds d- d\h'-1'\(ga | |
122 | . ds D- D\h'-1'\(hy | |
123 | . ds th \o'bp' | |
124 | . ds Th \o'LP' | |
125 | . ds ae ae | |
126 | . ds Ae AE | |
127 | .\} | |
128 | .rm #[ #] #H #V #F C | |
129 | .\" ======================================================================== | |
130 | .\" | |
131 | .IX Title "PERLOBJ 1" | |
132 | .TH PERLOBJ 1 "2006-01-07" "perl v5.8.8" "Perl Programmers Reference Guide" | |
133 | .SH "NAME" | |
134 | .IX Xref "object OOP" | |
135 | perlobj \- Perl objects | |
136 | .SH "DESCRIPTION" | |
137 | .IX Header "DESCRIPTION" | |
138 | First you need to understand what references are in Perl. | |
139 | See perlref for that. Second, if you still find the following | |
140 | reference work too complicated, a tutorial on object-oriented programming | |
141 | in Perl can be found in perltoot and perltooc. | |
142 | .PP | |
143 | If you're still with us, then | |
144 | here are three very simple definitions that you should find reassuring. | |
145 | .IP "1." 4 | |
146 | An object is simply a reference that happens to know which class it | |
147 | belongs to. | |
148 | .IP "2." 4 | |
149 | A class is simply a package that happens to provide methods to deal | |
150 | with object references. | |
151 | .IP "3." 4 | |
152 | A method is simply a subroutine that expects an object reference (or | |
153 | a package name, for class methods) as the first argument. | |
154 | .PP | |
155 | We'll cover these points now in more depth. | |
156 | .Sh "An Object is Simply a Reference" | |
157 | .IX Xref "object bless constructor new" | |
158 | .IX Subsection "An Object is Simply a Reference" | |
159 | Unlike say \*(C+, Perl doesn't provide any special syntax for | |
160 | constructors. A constructor is merely a subroutine that returns a | |
161 | reference to something \*(L"blessed\*(R" into a class, generally the | |
162 | class that the subroutine is defined in. Here is a typical | |
163 | constructor: | |
164 | .PP | |
165 | .Vb 2 | |
166 | \& package Critter; | |
167 | \& sub new { bless {} } | |
168 | .Ve | |
169 | .PP | |
170 | That word \f(CW\*(C`new\*(C'\fR isn't special. You could have written | |
171 | a construct this way, too: | |
172 | .PP | |
173 | .Vb 2 | |
174 | \& package Critter; | |
175 | \& sub spawn { bless {} } | |
176 | .Ve | |
177 | .PP | |
178 | This might even be preferable, because the \*(C+ programmers won't | |
179 | be tricked into thinking that \f(CW\*(C`new\*(C'\fR works in Perl as it does in \*(C+. | |
180 | It doesn't. We recommend that you name your constructors whatever | |
181 | makes sense in the context of the problem you're solving. For example, | |
182 | constructors in the Tk extension to Perl are named after the widgets | |
183 | they create. | |
184 | .PP | |
185 | One thing that's different about Perl constructors compared with those in | |
186 | \&\*(C+ is that in Perl, they have to allocate their own memory. (The other | |
187 | things is that they don't automatically call overridden base-class | |
188 | constructors.) The \f(CW\*(C`{}\*(C'\fR allocates an anonymous hash containing no | |
189 | key/value pairs, and returns it The \fIbless()\fR takes that reference and | |
190 | tells the object it references that it's now a Critter, and returns | |
191 | the reference. This is for convenience, because the referenced object | |
192 | itself knows that it has been blessed, and the reference to it could | |
193 | have been returned directly, like this: | |
194 | .PP | |
195 | .Vb 5 | |
196 | \& sub new { | |
197 | \& my $self = {}; | |
198 | \& bless $self; | |
199 | \& return $self; | |
200 | \& } | |
201 | .Ve | |
202 | .PP | |
203 | You often see such a thing in more complicated constructors | |
204 | that wish to call methods in the class as part of the construction: | |
205 | .PP | |
206 | .Vb 6 | |
207 | \& sub new { | |
208 | \& my $self = {}; | |
209 | \& bless $self; | |
210 | \& $self->initialize(); | |
211 | \& return $self; | |
212 | \& } | |
213 | .Ve | |
214 | .PP | |
215 | If you care about inheritance (and you should; see | |
216 | \&\*(L"Modules: Creation, Use, and Abuse\*(R" in perlmodlib), | |
217 | then you want to use the two-arg form of bless | |
218 | so that your constructors may be inherited: | |
219 | .PP | |
220 | .Vb 7 | |
221 | \& sub new { | |
222 | \& my $class = shift; | |
223 | \& my $self = {}; | |
224 | \& bless $self, $class; | |
225 | \& $self->initialize(); | |
226 | \& return $self; | |
227 | \& } | |
228 | .Ve | |
229 | .PP | |
230 | Or if you expect people to call not just \f(CW\*(C`CLASS\->new()\*(C'\fR but also | |
231 | \&\f(CW\*(C`$obj\->new()\*(C'\fR, then use something like the following. (Note that using | |
232 | this to call \fInew()\fR on an instance does not automatically perform any | |
233 | copying. If you want a shallow or deep copy of an object, you'll have to | |
234 | specifically allow for that.) The \fIinitialize()\fR method used will be of | |
235 | whatever \f(CW$class\fR we blessed the object into: | |
236 | .PP | |
237 | .Vb 8 | |
238 | \& sub new { | |
239 | \& my $this = shift; | |
240 | \& my $class = ref($this) || $this; | |
241 | \& my $self = {}; | |
242 | \& bless $self, $class; | |
243 | \& $self->initialize(); | |
244 | \& return $self; | |
245 | \& } | |
246 | .Ve | |
247 | .PP | |
248 | Within the class package, the methods will typically deal with the | |
249 | reference as an ordinary reference. Outside the class package, | |
250 | the reference is generally treated as an opaque value that may | |
251 | be accessed only through the class's methods. | |
252 | .PP | |
253 | Although a constructor can in theory re-bless a referenced object | |
254 | currently belonging to another class, this is almost certainly going | |
255 | to get you into trouble. The new class is responsible for all | |
256 | cleanup later. The previous blessing is forgotten, as an object | |
257 | may belong to only one class at a time. (Although of course it's | |
258 | free to inherit methods from many classes.) If you find yourself | |
259 | having to do this, the parent class is probably misbehaving, though. | |
260 | .PP | |
261 | A clarification: Perl objects are blessed. References are not. Objects | |
262 | know which package they belong to. References do not. The \fIbless()\fR | |
263 | function uses the reference to find the object. Consider | |
264 | the following example: | |
265 | .PP | |
266 | .Vb 4 | |
267 | \& $a = {}; | |
268 | \& $b = $a; | |
269 | \& bless $a, BLAH; | |
270 | \& print "\e$b is a ", ref($b), "\en"; | |
271 | .Ve | |
272 | .PP | |
273 | This reports \f(CW$b\fR as being a \s-1BLAH\s0, so obviously \fIbless()\fR | |
274 | operated on the object and not on the reference. | |
275 | .Sh "A Class is Simply a Package" | |
276 | .IX Xref "class package @ISA inheritance" | |
277 | .IX Subsection "A Class is Simply a Package" | |
278 | Unlike say \*(C+, Perl doesn't provide any special syntax for class | |
279 | definitions. You use a package as a class by putting method | |
280 | definitions into the class. | |
281 | .PP | |
282 | There is a special array within each package called \f(CW@ISA\fR, which says | |
283 | where else to look for a method if you can't find it in the current | |
284 | package. This is how Perl implements inheritance. Each element of the | |
285 | \&\f(CW@ISA\fR array is just the name of another package that happens to be a | |
286 | class package. The classes are searched (depth first) for missing | |
287 | methods in the order that they occur in \f(CW@ISA\fR. The classes accessible | |
288 | through \f(CW@ISA\fR are known as base classes of the current class. | |
289 | .PP | |
290 | All classes implicitly inherit from class \f(CW\*(C`UNIVERSAL\*(C'\fR as their | |
291 | last base class. Several commonly used methods are automatically | |
292 | supplied in the \s-1UNIVERSAL\s0 class; see \*(L"Default \s-1UNIVERSAL\s0 methods\*(R" for | |
293 | more details. | |
294 | .IX Xref "UNIVERSAL base class class, base" | |
295 | .PP | |
296 | If a missing method is found in a base class, it is cached | |
297 | in the current class for efficiency. Changing \f(CW@ISA\fR or defining new | |
298 | subroutines invalidates the cache and causes Perl to do the lookup again. | |
299 | .PP | |
300 | If neither the current class, its named base classes, nor the \s-1UNIVERSAL\s0 | |
301 | class contains the requested method, these three places are searched | |
302 | all over again, this time looking for a method named \s-1\fIAUTOLOAD\s0()\fR. If an | |
303 | \&\s-1AUTOLOAD\s0 is found, this method is called on behalf of the missing method, | |
304 | setting the package global \f(CW$AUTOLOAD\fR to be the fully qualified name of | |
305 | the method that was intended to be called. | |
306 | .IX Xref "AUTOLOAD" | |
307 | .PP | |
308 | If none of that works, Perl finally gives up and complains. | |
309 | .PP | |
310 | If you want to stop the \s-1AUTOLOAD\s0 inheritance say simply | |
311 | .IX Xref "AUTOLOAD" | |
312 | .PP | |
313 | .Vb 1 | |
314 | \& sub AUTOLOAD; | |
315 | .Ve | |
316 | .PP | |
317 | and the call will die using the name of the sub being called. | |
318 | .PP | |
319 | Perl classes do method inheritance only. Data inheritance is left up | |
320 | to the class itself. By and large, this is not a problem in Perl, | |
321 | because most classes model the attributes of their object using an | |
322 | anonymous hash, which serves as its own little namespace to be carved up | |
323 | by the various classes that might want to do something with the object. | |
324 | The only problem with this is that you can't sure that you aren't using | |
325 | a piece of the hash that isn't already used. A reasonable workaround | |
326 | is to prepend your fieldname in the hash with the package name. | |
327 | .IX Xref "inheritance, method inheritance, data" | |
328 | .PP | |
329 | .Vb 4 | |
330 | \& sub bump { | |
331 | \& my $self = shift; | |
332 | \& $self->{ __PACKAGE__ . ".count"}++; | |
333 | \& } | |
334 | .Ve | |
335 | .Sh "A Method is Simply a Subroutine" | |
336 | .IX Xref "method" | |
337 | .IX Subsection "A Method is Simply a Subroutine" | |
338 | Unlike say \*(C+, Perl doesn't provide any special syntax for method | |
339 | definition. (It does provide a little syntax for method invocation | |
340 | though. More on that later.) A method expects its first argument | |
341 | to be the object (reference) or package (string) it is being invoked | |
342 | on. There are two ways of calling methods, which we'll call class | |
343 | methods and instance methods. | |
344 | .PP | |
345 | A class method expects a class name as the first argument. It | |
346 | provides functionality for the class as a whole, not for any | |
347 | individual object belonging to the class. Constructors are often | |
348 | class methods, but see perltoot and perltooc for alternatives. | |
349 | Many class methods simply ignore their first argument, because they | |
350 | already know what package they're in and don't care what package | |
351 | they were invoked via. (These aren't necessarily the same, because | |
352 | class methods follow the inheritance tree just like ordinary instance | |
353 | methods.) Another typical use for class methods is to look up an | |
354 | object by name: | |
355 | .PP | |
356 | .Vb 4 | |
357 | \& sub find { | |
358 | \& my ($class, $name) = @_; | |
359 | \& $objtable{$name}; | |
360 | \& } | |
361 | .Ve | |
362 | .PP | |
363 | An instance method expects an object reference as its first argument. | |
364 | Typically it shifts the first argument into a \*(L"self\*(R" or \*(L"this\*(R" variable, | |
365 | and then uses that as an ordinary reference. | |
366 | .PP | |
367 | .Vb 7 | |
368 | \& sub display { | |
369 | \& my $self = shift; | |
370 | \& my @keys = @_ ? @_ : sort keys %$self; | |
371 | \& foreach $key (@keys) { | |
372 | \& print "\et$key => $self->{$key}\en"; | |
373 | \& } | |
374 | \& } | |
375 | .Ve | |
376 | .Sh "Method Invocation" | |
377 | .IX Xref "invocation method arrow ->" | |
378 | .IX Subsection "Method Invocation" | |
379 | For various historical and other reasons, Perl offers two equivalent | |
380 | ways to write a method call. The simpler and more common way is to use | |
381 | the arrow notation: | |
382 | .PP | |
383 | .Vb 2 | |
384 | \& my $fred = Critter->find("Fred"); | |
385 | \& $fred->display("Height", "Weight"); | |
386 | .Ve | |
387 | .PP | |
388 | You should already be familiar with the use of the \f(CW\*(C`\->\*(C'\fR operator with | |
389 | references. In fact, since \f(CW$fred\fR above is a reference to an object, | |
390 | you could think of the method call as just another form of | |
391 | dereferencing. | |
392 | .PP | |
393 | Whatever is on the left side of the arrow, whether a reference or a | |
394 | class name, is passed to the method subroutine as its first argument. | |
395 | So the above code is mostly equivalent to: | |
396 | .PP | |
397 | .Vb 2 | |
398 | \& my $fred = Critter::find("Critter", "Fred"); | |
399 | \& Critter::display($fred, "Height", "Weight"); | |
400 | .Ve | |
401 | .PP | |
402 | How does Perl know which package the subroutine is in? By looking at | |
403 | the left side of the arrow, which must be either a package name or a | |
404 | reference to an object, i.e. something that has been blessed to a | |
405 | package. Either way, that's the package where Perl starts looking. If | |
406 | that package has no subroutine with that name, Perl starts looking for | |
407 | it in any base classes of that package, and so on. | |
408 | .PP | |
409 | If you need to, you \fIcan\fR force Perl to start looking in some other package: | |
410 | .PP | |
411 | .Vb 2 | |
412 | \& my $barney = MyCritter->Critter::find("Barney"); | |
413 | \& $barney->Critter::display("Height", "Weight"); | |
414 | .Ve | |
415 | .PP | |
416 | Here \f(CW\*(C`MyCritter\*(C'\fR is presumably a subclass of \f(CW\*(C`Critter\*(C'\fR that defines | |
417 | its own versions of \fIfind()\fR and \fIdisplay()\fR. We haven't specified what | |
418 | those methods do, but that doesn't matter above since we've forced Perl | |
419 | to start looking for the subroutines in \f(CW\*(C`Critter\*(C'\fR. | |
420 | .PP | |
421 | As a special case of the above, you may use the \f(CW\*(C`SUPER\*(C'\fR pseudo-class to | |
422 | tell Perl to start looking for the method in the packages named in the | |
423 | current class's \f(CW@ISA\fR list. | |
424 | .IX Xref "SUPER" | |
425 | .PP | |
426 | .Vb 2 | |
427 | \& package MyCritter; | |
428 | \& use base 'Critter'; # sets @MyCritter::ISA = ('Critter'); | |
429 | .Ve | |
430 | .PP | |
431 | .Vb 4 | |
432 | \& sub display { | |
433 | \& my ($self, @args) = @_; | |
434 | \& $self->SUPER::display("Name", @args); | |
435 | \& } | |
436 | .Ve | |
437 | .PP | |
438 | It is important to note that \f(CW\*(C`SUPER\*(C'\fR refers to the superclass(es) of the | |
439 | \&\fIcurrent package\fR and not to the superclass(es) of the object. Also, the | |
440 | \&\f(CW\*(C`SUPER\*(C'\fR pseudo-class can only currently be used as a modifier to a method | |
441 | name, but not in any of the other ways that class names are normally used, | |
442 | eg: | |
443 | .IX Xref "SUPER" | |
444 | .PP | |
445 | .Vb 3 | |
446 | \& something->SUPER::method(...); # OK | |
447 | \& SUPER::method(...); # WRONG | |
448 | \& SUPER->method(...); # WRONG | |
449 | .Ve | |
450 | .PP | |
451 | Instead of a class name or an object reference, you can also use any | |
452 | expression that returns either of those on the left side of the arrow. | |
453 | So the following statement is valid: | |
454 | .PP | |
455 | .Vb 1 | |
456 | \& Critter->find("Fred")->display("Height", "Weight"); | |
457 | .Ve | |
458 | .PP | |
459 | and so is the following: | |
460 | .PP | |
461 | .Vb 1 | |
462 | \& my $fred = (reverse "rettirC")->find(reverse "derF"); | |
463 | .Ve | |
464 | .PP | |
465 | The right side of the arrow typically is the method name, but a simple | |
466 | scalar variable containing either the method name or a subroutine | |
467 | reference can also be used. | |
468 | .Sh "Indirect Object Syntax" | |
469 | .IX Xref "indirect object syntax invocation, indirect indirect" | |
470 | .IX Subsection "Indirect Object Syntax" | |
471 | The other way to invoke a method is by using the so-called \*(L"indirect | |
472 | object\*(R" notation. This syntax was available in Perl 4 long before | |
473 | objects were introduced, and is still used with filehandles like this: | |
474 | .PP | |
475 | .Vb 1 | |
476 | \& print STDERR "help!!!\en"; | |
477 | .Ve | |
478 | .PP | |
479 | The same syntax can be used to call either object or class methods. | |
480 | .PP | |
481 | .Vb 2 | |
482 | \& my $fred = find Critter "Fred"; | |
483 | \& display $fred "Height", "Weight"; | |
484 | .Ve | |
485 | .PP | |
486 | Notice that there is no comma between the object or class name and the | |
487 | parameters. This is how Perl can tell you want an indirect method call | |
488 | instead of an ordinary subroutine call. | |
489 | .PP | |
490 | But what if there are no arguments? In that case, Perl must guess what | |
491 | you want. Even worse, it must make that guess \fIat compile time\fR. | |
492 | Usually Perl gets it right, but when it doesn't you get a function | |
493 | call compiled as a method, or vice versa. This can introduce subtle bugs | |
494 | that are hard to detect. | |
495 | .PP | |
496 | For example, a call to a method \f(CW\*(C`new\*(C'\fR in indirect notation \*(-- as \*(C+ | |
497 | programmers are wont to make \*(-- can be miscompiled into a subroutine | |
498 | call if there's already a \f(CW\*(C`new\*(C'\fR function in scope. You'd end up | |
499 | calling the current package's \f(CW\*(C`new\*(C'\fR as a subroutine, rather than the | |
500 | desired class's method. The compiler tries to cheat by remembering | |
501 | bareword \f(CW\*(C`require\*(C'\fRs, but the grief when it messes up just isn't worth the | |
502 | years of debugging it will take you to track down such subtle bugs. | |
503 | .PP | |
504 | There is another problem with this syntax: the indirect object is | |
505 | limited to a name, a scalar variable, or a block, because it would have | |
506 | to do too much lookahead otherwise, just like any other postfix | |
507 | dereference in the language. (These are the same quirky rules as are | |
508 | used for the filehandle slot in functions like \f(CW\*(C`print\*(C'\fR and \f(CW\*(C`printf\*(C'\fR.) | |
509 | This can lead to horribly confusing precedence problems, as in these | |
510 | next two lines: | |
511 | .PP | |
512 | .Vb 2 | |
513 | \& move $obj->{FIELD}; # probably wrong! | |
514 | \& move $ary[$i]; # probably wrong! | |
515 | .Ve | |
516 | .PP | |
517 | Those actually parse as the very surprising: | |
518 | .PP | |
519 | .Vb 2 | |
520 | \& $obj->move->{FIELD}; # Well, lookee here | |
521 | \& $ary->move([$i]); # Didn't expect this one, eh? | |
522 | .Ve | |
523 | .PP | |
524 | Rather than what you might have expected: | |
525 | .PP | |
526 | .Vb 2 | |
527 | \& $obj->{FIELD}->move(); # You should be so lucky. | |
528 | \& $ary[$i]->move; # Yeah, sure. | |
529 | .Ve | |
530 | .PP | |
531 | To get the correct behavior with indirect object syntax, you would have | |
532 | to use a block around the indirect object: | |
533 | .PP | |
534 | .Vb 2 | |
535 | \& move {$obj->{FIELD}}; | |
536 | \& move {$ary[$i]}; | |
537 | .Ve | |
538 | .PP | |
539 | Even then, you still have the same potential problem if there happens to | |
540 | be a function named \f(CW\*(C`move\*(C'\fR in the current package. \fBThe \f(CB\*(C`\->\*(C'\fB | |
541 | notation suffers from neither of these disturbing ambiguities, so we | |
542 | recommend you use it exclusively.\fR However, you may still end up having | |
543 | to read code using the indirect object notation, so it's important to be | |
544 | familiar with it. | |
545 | .Sh "Default \s-1UNIVERSAL\s0 methods" | |
546 | .IX Xref "UNIVERSAL" | |
547 | .IX Subsection "Default UNIVERSAL methods" | |
548 | The \f(CW\*(C`UNIVERSAL\*(C'\fR package automatically contains the following methods that | |
549 | are inherited by all other classes: | |
550 | .IP "isa(\s-1CLASS\s0)" 4 | |
551 | .IX Xref "isa" | |
552 | .IX Item "isa(CLASS)" | |
553 | \&\f(CW\*(C`isa\*(C'\fR returns \fItrue\fR if its object is blessed into a subclass of \f(CW\*(C`CLASS\*(C'\fR | |
554 | .Sp | |
555 | You can also call \f(CW\*(C`UNIVERSAL::isa\*(C'\fR as a subroutine with two arguments. Of | |
556 | course, this will do the wrong thing if someone has overridden \f(CW\*(C`isa\*(C'\fR in a | |
557 | class, so don't do it. | |
558 | .Sp | |
559 | If you need to determine whether you've received a valid invocant, use the | |
560 | \&\f(CW\*(C`blessed\*(C'\fR function from Scalar::Util: | |
561 | .IX Xref "invocant blessed" | |
562 | .Sp | |
563 | .Vb 3 | |
564 | \& if (blessed($ref) && $ref->isa( 'Some::Class')) { | |
565 | \& # ... | |
566 | \& } | |
567 | .Ve | |
568 | .Sp | |
569 | \&\f(CW\*(C`blessed\*(C'\fR returns the name of the package the argument has been | |
570 | blessed into, or \f(CW\*(C`undef\*(C'\fR. | |
571 | .IP "can(\s-1METHOD\s0)" 4 | |
572 | .IX Xref "can" | |
573 | .IX Item "can(METHOD)" | |
574 | \&\f(CW\*(C`can\*(C'\fR checks to see if its object has a method called \f(CW\*(C`METHOD\*(C'\fR, | |
575 | if it does then a reference to the sub is returned, if it does not then | |
576 | \&\fIundef\fR is returned. | |
577 | .Sp | |
578 | \&\f(CW\*(C`UNIVERSAL::can\*(C'\fR can also be called as a subroutine with two arguments. It'll | |
579 | always return \fIundef\fR if its first argument isn't an object or a class name. | |
580 | The same caveats for calling \f(CW\*(C`UNIVERSAL::isa\*(C'\fR directly apply here, too. | |
581 | .IP "\s-1VERSION\s0( [\s-1NEED\s0] )" 4 | |
582 | .IX Xref "VERSION" | |
583 | .IX Item "VERSION( [NEED] )" | |
584 | \&\f(CW\*(C`VERSION\*(C'\fR returns the version number of the class (package). If the | |
585 | \&\s-1NEED\s0 argument is given then it will check that the current version (as | |
586 | defined by the \f(CW$VERSION\fR variable in the given package) not less than | |
587 | \&\s-1NEED\s0; it will die if this is not the case. This method is normally | |
588 | called as a class method. This method is called automatically by the | |
589 | \&\f(CW\*(C`VERSION\*(C'\fR form of \f(CW\*(C`use\*(C'\fR. | |
590 | .Sp | |
591 | .Vb 3 | |
592 | \& use A 1.2 qw(some imported subs); | |
593 | \& # implies: | |
594 | \& A->VERSION(1.2); | |
595 | .Ve | |
596 | .PP | |
597 | \&\fB\s-1NOTE:\s0\fR \f(CW\*(C`can\*(C'\fR directly uses Perl's internal code for method lookup, and | |
598 | \&\f(CW\*(C`isa\*(C'\fR uses a very similar method and cache-ing strategy. This may cause | |
599 | strange effects if the Perl code dynamically changes \f(CW@ISA\fR in any package. | |
600 | .PP | |
601 | You may add other methods to the \s-1UNIVERSAL\s0 class via Perl or \s-1XS\s0 code. | |
602 | You do not need to \f(CW\*(C`use UNIVERSAL\*(C'\fR to make these methods | |
603 | available to your program (and you should not do so). | |
604 | .Sh "Destructors" | |
605 | .IX Xref "destructor DESTROY" | |
606 | .IX Subsection "Destructors" | |
607 | When the last reference to an object goes away, the object is | |
608 | automatically destroyed. (This may even be after you exit, if you've | |
609 | stored references in global variables.) If you want to capture control | |
610 | just before the object is freed, you may define a \s-1DESTROY\s0 method in | |
611 | your class. It will automatically be called at the appropriate moment, | |
612 | and you can do any extra cleanup you need to do. Perl passes a reference | |
613 | to the object under destruction as the first (and only) argument. Beware | |
614 | that the reference is a read-only value, and cannot be modified by | |
615 | manipulating \f(CW$_[0]\fR within the destructor. The object itself (i.e. | |
616 | the thingy the reference points to, namely \f(CW\*(C`${$_[0]}\*(C'\fR, \f(CW\*(C`@{$_[0]}\*(C'\fR, | |
617 | \&\f(CW\*(C`%{$_[0]}\*(C'\fR etc.) is not similarly constrained. | |
618 | .PP | |
619 | Since \s-1DESTROY\s0 methods can be called at unpredictable times, it is | |
620 | important that you localise any global variables that the method may | |
621 | update. In particular, localise \f(CW$@\fR if you use \f(CW\*(C`eval {}\*(C'\fR and | |
622 | localise \f(CW$?\fR if you use \f(CW\*(C`system\*(C'\fR or backticks. | |
623 | .PP | |
624 | If you arrange to re-bless the reference before the destructor returns, | |
625 | perl will again call the \s-1DESTROY\s0 method for the re-blessed object after | |
626 | the current one returns. This can be used for clean delegation of | |
627 | object destruction, or for ensuring that destructors in the base classes | |
628 | of your choosing get called. Explicitly calling \s-1DESTROY\s0 is also possible, | |
629 | but is usually never needed. | |
630 | .PP | |
631 | Do not confuse the previous discussion with how objects \fI\s-1CONTAINED\s0\fR in the current | |
632 | one are destroyed. Such objects will be freed and destroyed automatically | |
633 | when the current object is freed, provided no other references to them exist | |
634 | elsewhere. | |
635 | .Sh "Summary" | |
636 | .IX Subsection "Summary" | |
637 | That's about all there is to it. Now you need just to go off and buy a | |
638 | book about object-oriented design methodology, and bang your forehead | |
639 | with it for the next six months or so. | |
640 | .Sh "Two-Phased Garbage Collection" | |
641 | .IX Xref "garbage collection GC circular reference reference, circular DESTROY destructor" | |
642 | .IX Subsection "Two-Phased Garbage Collection" | |
643 | For most purposes, Perl uses a fast and simple, reference-based | |
644 | garbage collection system. That means there's an extra | |
645 | dereference going on at some level, so if you haven't built | |
646 | your Perl executable using your C compiler's \f(CW\*(C`\-O\*(C'\fR flag, performance | |
647 | will suffer. If you \fIhave\fR built Perl with \f(CW\*(C`cc \-O\*(C'\fR, then this | |
648 | probably won't matter. | |
649 | .PP | |
650 | A more serious concern is that unreachable memory with a non-zero | |
651 | reference count will not normally get freed. Therefore, this is a bad | |
652 | idea: | |
653 | .PP | |
654 | .Vb 4 | |
655 | \& { | |
656 | \& my $a; | |
657 | \& $a = \e$a; | |
658 | \& } | |
659 | .Ve | |
660 | .PP | |
661 | Even thought \f(CW$a\fR \fIshould\fR go away, it can't. When building recursive data | |
662 | structures, you'll have to break the self-reference yourself explicitly | |
663 | if you don't care to leak. For example, here's a self-referential | |
664 | node such as one might use in a sophisticated tree structure: | |
665 | .PP | |
666 | .Vb 7 | |
667 | \& sub new_node { | |
668 | \& my $class = shift; | |
669 | \& my $node = {}; | |
670 | \& $node->{LEFT} = $node->{RIGHT} = $node; | |
671 | \& $node->{DATA} = [ @_ ]; | |
672 | \& return bless $node => $class; | |
673 | \& } | |
674 | .Ve | |
675 | .PP | |
676 | If you create nodes like that, they (currently) won't go away unless you | |
677 | break their self reference yourself. (In other words, this is not to be | |
678 | construed as a feature, and you shouldn't depend on it.) | |
679 | .PP | |
680 | Almost. | |
681 | .PP | |
682 | When an interpreter thread finally shuts down (usually when your program | |
683 | exits), then a rather costly but complete mark-and-sweep style of garbage | |
684 | collection is performed, and everything allocated by that thread gets | |
685 | destroyed. This is essential to support Perl as an embedded or a | |
686 | multithreadable language. For example, this program demonstrates Perl's | |
687 | two-phased garbage collection: | |
688 | .PP | |
689 | .Vb 2 | |
690 | \& #!/usr/bin/perl | |
691 | \& package Subtle; | |
692 | .Ve | |
693 | .PP | |
694 | .Vb 6 | |
695 | \& sub new { | |
696 | \& my $test; | |
697 | \& $test = \e$test; | |
698 | \& warn "CREATING " . \e$test; | |
699 | \& return bless \e$test; | |
700 | \& } | |
701 | .Ve | |
702 | .PP | |
703 | .Vb 4 | |
704 | \& sub DESTROY { | |
705 | \& my $self = shift; | |
706 | \& warn "DESTROYING $self"; | |
707 | \& } | |
708 | .Ve | |
709 | .PP | |
710 | .Vb 1 | |
711 | \& package main; | |
712 | .Ve | |
713 | .PP | |
714 | .Vb 7 | |
715 | \& warn "starting program"; | |
716 | \& { | |
717 | \& my $a = Subtle->new; | |
718 | \& my $b = Subtle->new; | |
719 | \& $$a = 0; # break selfref | |
720 | \& warn "leaving block"; | |
721 | \& } | |
722 | .Ve | |
723 | .PP | |
724 | .Vb 3 | |
725 | \& warn "just exited block"; | |
726 | \& warn "time to die..."; | |
727 | \& exit; | |
728 | .Ve | |
729 | .PP | |
730 | When run as \fI/foo/test\fR, the following output is produced: | |
731 | .PP | |
732 | .Vb 8 | |
733 | \& starting program at /foo/test line 18. | |
734 | \& CREATING SCALAR(0x8e5b8) at /foo/test line 7. | |
735 | \& CREATING SCALAR(0x8e57c) at /foo/test line 7. | |
736 | \& leaving block at /foo/test line 23. | |
737 | \& DESTROYING Subtle=SCALAR(0x8e5b8) at /foo/test line 13. | |
738 | \& just exited block at /foo/test line 26. | |
739 | \& time to die... at /foo/test line 27. | |
740 | \& DESTROYING Subtle=SCALAR(0x8e57c) during global destruction. | |
741 | .Ve | |
742 | .PP | |
743 | Notice that \*(L"global destruction\*(R" bit there? That's the thread | |
744 | garbage collector reaching the unreachable. | |
745 | .PP | |
746 | Objects are always destructed, even when regular refs aren't. Objects | |
747 | are destructed in a separate pass before ordinary refs just to | |
748 | prevent object destructors from using refs that have been themselves | |
749 | destructed. Plain refs are only garbage-collected if the destruct level | |
750 | is greater than 0. You can test the higher levels of global destruction | |
751 | by setting the \s-1PERL_DESTRUCT_LEVEL\s0 environment variable, presuming | |
752 | \&\f(CW\*(C`\-DDEBUGGING\*(C'\fR was enabled during perl build time. | |
753 | See \*(L"\s-1PERL_DESTRUCT_LEVEL\s0\*(R" in perlhack for more information. | |
754 | .PP | |
755 | A more complete garbage collection strategy will be implemented | |
756 | at a future date. | |
757 | .PP | |
758 | In the meantime, the best solution is to create a non-recursive container | |
759 | class that holds a pointer to the self-referential data structure. | |
760 | Define a \s-1DESTROY\s0 method for the containing object's class that manually | |
761 | breaks the circularities in the self-referential structure. | |
762 | .SH "SEE ALSO" | |
763 | .IX Header "SEE ALSO" | |
764 | A kinder, gentler tutorial on object-oriented programming in Perl can | |
765 | be found in perltoot, perlboot and perltooc. You should | |
766 | also check out perlbot for other object tricks, traps, and tips, as | |
767 | well as perlmodlib for some style guides on constructing both | |
768 | modules and classes. |