1PERLOBJ(1) Perl Programmers Reference Guide PERLOBJ(1)
2
3
4
6 perlobj - Perl objects
7
9 First you need to understand what references are in Perl. See perlref
10 for that. Second, if you still find the following reference work too
11 complicated, a tutorial on object-oriented programming in Perl can be
12 found in perltoot and perltooc.
13
14 If you're still with us, then here are three very simple definitions
15 that you should find reassuring.
16
17 1. An object is simply a reference that happens to know which class it
18 belongs to.
19
20 2. A class is simply a package that happens to provide methods to deal
21 with object references.
22
23 3. A method is simply a subroutine that expects an object reference
24 (or a package name, for class methods) as the first argument.
25
26 We'll cover these points now in more depth.
27
28 An Object is Simply a Reference
29
30 Unlike say C++, Perl doesn't provide any special syntax for construc‐
31 tors. A constructor is merely a subroutine that returns a reference to
32 something "blessed" into a class, generally the class that the subrou‐
33 tine is defined in. Here is a typical constructor:
34
35 package Critter;
36 sub new { bless {} }
37
38 That word "new" isn't special. You could have written a construct this
39 way, too:
40
41 package Critter;
42 sub spawn { bless {} }
43
44 This might even be preferable, because the C++ programmers won't be
45 tricked into thinking that "new" works in Perl as it does in C++. It
46 doesn't. We recommend that you name your constructors whatever makes
47 sense in the context of the problem you're solving. For example, con‐
48 structors in the Tk extension to Perl are named after the widgets they
49 create.
50
51 One thing that's different about Perl constructors compared with those
52 in C++ is that in Perl, they have to allocate their own memory. (The
53 other things is that they don't automatically call overridden base-
54 class constructors.) The "{}" allocates an anonymous hash containing
55 no key/value pairs, and returns it The bless() takes that reference
56 and tells the object it references that it's now a Critter, and returns
57 the reference. This is for convenience, because the referenced object
58 itself knows that it has been blessed, and the reference to it could
59 have been returned directly, like this:
60
61 sub new {
62 my $self = {};
63 bless $self;
64 return $self;
65 }
66
67 You often see such a thing in more complicated constructors that wish
68 to call methods in the class as part of the construction:
69
70 sub new {
71 my $self = {};
72 bless $self;
73 $self->initialize();
74 return $self;
75 }
76
77 If you care about inheritance (and you should; see "Modules: Creation,
78 Use, and Abuse" in perlmodlib), then you want to use the two-arg form
79 of bless so that your constructors may be inherited:
80
81 sub new {
82 my $class = shift;
83 my $self = {};
84 bless $self, $class;
85 $self->initialize();
86 return $self;
87 }
88
89 Or if you expect people to call not just "CLASS->new()" but also
90 "$obj->new()", then use something like the following. (Note that using
91 this to call new() on an instance does not automatically perform any
92 copying. If you want a shallow or deep copy of an object, you'll have
93 to specifically allow for that.) The initialize() method used will be
94 of whatever $class we blessed the object into:
95
96 sub new {
97 my $this = shift;
98 my $class = ref($this) ⎪⎪ $this;
99 my $self = {};
100 bless $self, $class;
101 $self->initialize();
102 return $self;
103 }
104
105 Within the class package, the methods will typically deal with the ref‐
106 erence as an ordinary reference. Outside the class package, the refer‐
107 ence is generally treated as an opaque value that may be accessed only
108 through the class's methods.
109
110 Although a constructor can in theory re-bless a referenced object cur‐
111 rently belonging to another class, this is almost certainly going to
112 get you into trouble. The new class is responsible for all cleanup
113 later. The previous blessing is forgotten, as an object may belong to
114 only one class at a time. (Although of course it's free to inherit
115 methods from many classes.) If you find yourself having to do this,
116 the parent class is probably misbehaving, though.
117
118 A clarification: Perl objects are blessed. References are not.
119 Objects know which package they belong to. References do not. The
120 bless() function uses the reference to find the object. Consider the
121 following example:
122
123 $a = {};
124 $b = $a;
125 bless $a, BLAH;
126 print "\$b is a ", ref($b), "\n";
127
128 This reports $b as being a BLAH, so obviously bless() operated on the
129 object and not on the reference.
130
131 A Class is Simply a Package
132
133 Unlike say C++, Perl doesn't provide any special syntax for class defi‐
134 nitions. You use a package as a class by putting method definitions
135 into the class.
136
137 There is a special array within each package called @ISA, which says
138 where else to look for a method if you can't find it in the current
139 package. This is how Perl implements inheritance. Each element of the
140 @ISA array is just the name of another package that happens to be a
141 class package. The classes are searched (depth first) for missing
142 methods in the order that they occur in @ISA. The classes accessible
143 through @ISA are known as base classes of the current class.
144
145 All classes implicitly inherit from class "UNIVERSAL" as their last
146 base class. Several commonly used methods are automatically supplied
147 in the UNIVERSAL class; see "Default UNIVERSAL methods" for more
148 details.
149
150 If a missing method is found in a base class, it is cached in the cur‐
151 rent class for efficiency. Changing @ISA or defining new subroutines
152 invalidates the cache and causes Perl to do the lookup again.
153
154 If neither the current class, its named base classes, nor the UNIVERSAL
155 class contains the requested method, these three places are searched
156 all over again, this time looking for a method named AUTOLOAD(). If an
157 AUTOLOAD is found, this method is called on behalf of the missing
158 method, setting the package global $AUTOLOAD to be the fully qualified
159 name of the method that was intended to be called.
160
161 If none of that works, Perl finally gives up and complains.
162
163 If you want to stop the AUTOLOAD inheritance say simply
164
165 sub AUTOLOAD;
166
167 and the call will die using the name of the sub being called.
168
169 Perl classes do method inheritance only. Data inheritance is left up
170 to the class itself. By and large, this is not a problem in Perl,
171 because most classes model the attributes of their object using an
172 anonymous hash, which serves as its own little namespace to be carved
173 up by the various classes that might want to do something with the
174 object. The only problem with this is that you can't sure that you
175 aren't using a piece of the hash that isn't already used. A reasonable
176 workaround is to prepend your fieldname in the hash with the package
177 name.
178
179 sub bump {
180 my $self = shift;
181 $self->{ __PACKAGE__ . ".count"}++;
182 }
183
184 A Method is Simply a Subroutine
185
186 Unlike say C++, Perl doesn't provide any special syntax for method def‐
187 inition. (It does provide a little syntax for method invocation
188 though. More on that later.) A method expects its first argument to
189 be the object (reference) or package (string) it is being invoked on.
190 There are two ways of calling methods, which we'll call class methods
191 and instance methods.
192
193 A class method expects a class name as the first argument. It provides
194 functionality for the class as a whole, not for any individual object
195 belonging to the class. Constructors are often class methods, but see
196 perltoot and perltooc for alternatives. Many class methods simply
197 ignore their first argument, because they already know what package
198 they're in and don't care what package they were invoked via. (These
199 aren't necessarily the same, because class methods follow the inheri‐
200 tance tree just like ordinary instance methods.) Another typical use
201 for class methods is to look up an object by name:
202
203 sub find {
204 my ($class, $name) = @_;
205 $objtable{$name};
206 }
207
208 An instance method expects an object reference as its first argument.
209 Typically it shifts the first argument into a "self" or "this" vari‐
210 able, and then uses that as an ordinary reference.
211
212 sub display {
213 my $self = shift;
214 my @keys = @_ ? @_ : sort keys %$self;
215 foreach $key (@keys) {
216 print "\t$key => $self->{$key}\n";
217 }
218 }
219
220 Method Invocation
221
222 For various historical and other reasons, Perl offers two equivalent
223 ways to write a method call. The simpler and more common way is to use
224 the arrow notation:
225
226 my $fred = Critter->find("Fred");
227 $fred->display("Height", "Weight");
228
229 You should already be familiar with the use of the "->" operator with
230 references. In fact, since $fred above is a reference to an object,
231 you could think of the method call as just another form of dereferenc‐
232 ing.
233
234 Whatever is on the left side of the arrow, whether a reference or a
235 class name, is passed to the method subroutine as its first argument.
236 So the above code is mostly equivalent to:
237
238 my $fred = Critter::find("Critter", "Fred");
239 Critter::display($fred, "Height", "Weight");
240
241 How does Perl know which package the subroutine is in? By looking at
242 the left side of the arrow, which must be either a package name or a
243 reference to an object, i.e. something that has been blessed to a pack‐
244 age. Either way, that's the package where Perl starts looking. If
245 that package has no subroutine with that name, Perl starts looking for
246 it in any base classes of that package, and so on.
247
248 If you need to, you can force Perl to start looking in some other pack‐
249 age:
250
251 my $barney = MyCritter->Critter::find("Barney");
252 $barney->Critter::display("Height", "Weight");
253
254 Here "MyCritter" is presumably a subclass of "Critter" that defines its
255 own versions of find() and display(). We haven't specified what those
256 methods do, but that doesn't matter above since we've forced Perl to
257 start looking for the subroutines in "Critter".
258
259 As a special case of the above, you may use the "SUPER" pseudo-class to
260 tell Perl to start looking for the method in the packages named in the
261 current class's @ISA list.
262
263 package MyCritter;
264 use base 'Critter'; # sets @MyCritter::ISA = ('Critter');
265
266 sub display {
267 my ($self, @args) = @_;
268 $self->SUPER::display("Name", @args);
269 }
270
271 It is important to note that "SUPER" refers to the superclass(es) of
272 the current package and not to the superclass(es) of the object. Also,
273 the "SUPER" pseudo-class can only currently be used as a modifier to a
274 method name, but not in any of the other ways that class names are nor‐
275 mally used, eg:
276
277 something->SUPER::method(...); # OK
278 SUPER::method(...); # WRONG
279 SUPER->method(...); # WRONG
280
281 Instead of a class name or an object reference, you can also use any
282 expression that returns either of those on the left side of the arrow.
283 So the following statement is valid:
284
285 Critter->find("Fred")->display("Height", "Weight");
286
287 and so is the following:
288
289 my $fred = (reverse "rettirC")->find(reverse "derF");
290
291 The right side of the arrow typically is the method name, but a simple
292 scalar variable containing either the method name or a subroutine ref‐
293 erence can also be used.
294
295 Indirect Object Syntax
296
297 The other way to invoke a method is by using the so-called "indirect
298 object" notation. This syntax was available in Perl 4 long before
299 objects were introduced, and is still used with filehandles like this:
300
301 print STDERR "help!!!\n";
302
303 The same syntax can be used to call either object or class methods.
304
305 my $fred = find Critter "Fred";
306 display $fred "Height", "Weight";
307
308 Notice that there is no comma between the object or class name and the
309 parameters. This is how Perl can tell you want an indirect method call
310 instead of an ordinary subroutine call.
311
312 But what if there are no arguments? In that case, Perl must guess what
313 you want. Even worse, it must make that guess at compile time. Usu‐
314 ally Perl gets it right, but when it doesn't you get a function call
315 compiled as a method, or vice versa. This can introduce subtle bugs
316 that are hard to detect.
317
318 For example, a call to a method "new" in indirect notation -- as C++
319 programmers are wont to make -- can be miscompiled into a subroutine
320 call if there's already a "new" function in scope. You'd end up call‐
321 ing the current package's "new" as a subroutine, rather than the
322 desired class's method. The compiler tries to cheat by remembering
323 bareword "require"s, but the grief when it messes up just isn't worth
324 the years of debugging it will take you to track down such subtle bugs.
325
326 There is another problem with this syntax: the indirect object is lim‐
327 ited to a name, a scalar variable, or a block, because it would have to
328 do too much lookahead otherwise, just like any other postfix derefer‐
329 ence in the language. (These are the same quirky rules as are used for
330 the filehandle slot in functions like "print" and "printf".) This can
331 lead to horribly confusing precedence problems, as in these next two
332 lines:
333
334 move $obj->{FIELD}; # probably wrong!
335 move $ary[$i]; # probably wrong!
336
337 Those actually parse as the very surprising:
338
339 $obj->move->{FIELD}; # Well, lookee here
340 $ary->move([$i]); # Didn't expect this one, eh?
341
342 Rather than what you might have expected:
343
344 $obj->{FIELD}->move(); # You should be so lucky.
345 $ary[$i]->move; # Yeah, sure.
346
347 To get the correct behavior with indirect object syntax, you would have
348 to use a block around the indirect object:
349
350 move {$obj->{FIELD}};
351 move {$ary[$i]};
352
353 Even then, you still have the same potential problem if there happens
354 to be a function named "move" in the current package. The "->" nota‐
355 tion suffers from neither of these disturbing ambiguities, so we recom‐
356 mend you use it exclusively. However, you may still end up having to
357 read code using the indirect object notation, so it's important to be
358 familiar with it.
359
360 Default UNIVERSAL methods
361
362 The "UNIVERSAL" package automatically contains the following methods
363 that are inherited by all other classes:
364
365 isa(CLASS)
366 "isa" returns true if its object is blessed into a subclass of
367 "CLASS"
368
369 You can also call "UNIVERSAL::isa" as a subroutine with two argu‐
370 ments. Of course, this will do the wrong thing if someone has
371 overridden "isa" in a class, so don't do it.
372
373 If you need to determine whether you've received a valid invocant,
374 use the "blessed" function from Scalar::Util:
375
376 if (blessed($ref) && $ref->isa( 'Some::Class')) {
377 # ...
378 }
379
380 "blessed" returns the name of the package the argument has been
381 blessed into, or "undef".
382
383 can(METHOD)
384 "can" checks to see if its object has a method called "METHOD", if
385 it does then a reference to the sub is returned, if it does not
386 then undef is returned.
387
388 "UNIVERSAL::can" can also be called as a subroutine with two argu‐
389 ments. It'll always return undef if its first argument isn't an
390 object or a class name. The same caveats for calling "UNIVER‐
391 SAL::isa" directly apply here, too.
392
393 VERSION( [NEED] )
394 "VERSION" returns the version number of the class (package). If
395 the NEED argument is given then it will check that the current ver‐
396 sion (as defined by the $VERSION variable in the given package) not
397 less than NEED; it will die if this is not the case. This method
398 is normally called as a class method. This method is called auto‐
399 matically by the "VERSION" form of "use".
400
401 use A 1.2 qw(some imported subs);
402 # implies:
403 A->VERSION(1.2);
404
405 NOTE: "can" directly uses Perl's internal code for method lookup, and
406 "isa" uses a very similar method and cache-ing strategy. This may cause
407 strange effects if the Perl code dynamically changes @ISA in any pack‐
408 age.
409
410 You may add other methods to the UNIVERSAL class via Perl or XS code.
411 You do not need to "use UNIVERSAL" to make these methods available to
412 your program (and you should not do so).
413
414 Destructors
415
416 When the last reference to an object goes away, the object is automati‐
417 cally destroyed. (This may even be after you exit, if you've stored
418 references in global variables.) If you want to capture control just
419 before the object is freed, you may define a DESTROY method in your
420 class. It will automatically be called at the appropriate moment, and
421 you can do any extra cleanup you need to do. Perl passes a reference
422 to the object under destruction as the first (and only) argument.
423 Beware that the reference is a read-only value, and cannot be modified
424 by manipulating $_[0] within the destructor. The object itself (i.e.
425 the thingy the reference points to, namely "${$_[0]}", "@{$_[0]}",
426 "%{$_[0]}" etc.) is not similarly constrained.
427
428 Since DESTROY methods can be called at unpredictable times, it is
429 important that you localise any global variables that the method may
430 update. In particular, localise $@ if you use "eval {}" and localise
431 $? if you use "system" or backticks.
432
433 If you arrange to re-bless the reference before the destructor returns,
434 perl will again call the DESTROY method for the re-blessed object after
435 the current one returns. This can be used for clean delegation of
436 object destruction, or for ensuring that destructors in the base
437 classes of your choosing get called. Explicitly calling DESTROY is
438 also possible, but is usually never needed.
439
440 Do not confuse the previous discussion with how objects CONTAINED in
441 the current one are destroyed. Such objects will be freed and
442 destroyed automatically when the current object is freed, provided no
443 other references to them exist elsewhere.
444
445 Summary
446
447 That's about all there is to it. Now you need just to go off and buy a
448 book about object-oriented design methodology, and bang your forehead
449 with it for the next six months or so.
450
451 Two-Phased Garbage Collection
452
453 For most purposes, Perl uses a fast and simple, reference-based garbage
454 collection system. That means there's an extra dereference going on at
455 some level, so if you haven't built your Perl executable using your C
456 compiler's "-O" flag, performance will suffer. If you have built Perl
457 with "cc -O", then this probably won't matter.
458
459 A more serious concern is that unreachable memory with a non-zero ref‐
460 erence count will not normally get freed. Therefore, this is a bad
461 idea:
462
463 {
464 my $a;
465 $a = \$a;
466 }
467
468 Even thought $a should go away, it can't. When building recursive data
469 structures, you'll have to break the self-reference yourself explicitly
470 if you don't care to leak. For example, here's a self-referential node
471 such as one might use in a sophisticated tree structure:
472
473 sub new_node {
474 my $class = shift;
475 my $node = {};
476 $node->{LEFT} = $node->{RIGHT} = $node;
477 $node->{DATA} = [ @_ ];
478 return bless $node => $class;
479 }
480
481 If you create nodes like that, they (currently) won't go away unless
482 you break their self reference yourself. (In other words, this is not
483 to be construed as a feature, and you shouldn't depend on it.)
484
485 Almost.
486
487 When an interpreter thread finally shuts down (usually when your pro‐
488 gram exits), then a rather costly but complete mark-and-sweep style of
489 garbage collection is performed, and everything allocated by that
490 thread gets destroyed. This is essential to support Perl as an embed‐
491 ded or a multithreadable language. For example, this program demon‐
492 strates Perl's two-phased garbage collection:
493
494 #!/usr/bin/perl
495 package Subtle;
496
497 sub new {
498 my $test;
499 $test = \$test;
500 warn "CREATING " . \$test;
501 return bless \$test;
502 }
503
504 sub DESTROY {
505 my $self = shift;
506 warn "DESTROYING $self";
507 }
508
509 package main;
510
511 warn "starting program";
512 {
513 my $a = Subtle->new;
514 my $b = Subtle->new;
515 $$a = 0; # break selfref
516 warn "leaving block";
517 }
518
519 warn "just exited block";
520 warn "time to die...";
521 exit;
522
523 When run as /foo/test, the following output is produced:
524
525 starting program at /foo/test line 18.
526 CREATING SCALAR(0x8e5b8) at /foo/test line 7.
527 CREATING SCALAR(0x8e57c) at /foo/test line 7.
528 leaving block at /foo/test line 23.
529 DESTROYING Subtle=SCALAR(0x8e5b8) at /foo/test line 13.
530 just exited block at /foo/test line 26.
531 time to die... at /foo/test line 27.
532 DESTROYING Subtle=SCALAR(0x8e57c) during global destruction.
533
534 Notice that "global destruction" bit there? That's the thread garbage
535 collector reaching the unreachable.
536
537 Objects are always destructed, even when regular refs aren't. Objects
538 are destructed in a separate pass before ordinary refs just to prevent
539 object destructors from using refs that have been themselves destruc‐
540 ted. Plain refs are only garbage-collected if the destruct level is
541 greater than 0. You can test the higher levels of global destruction
542 by setting the PERL_DESTRUCT_LEVEL environment variable, presuming
543 "-DDEBUGGING" was enabled during perl build time. See
544 "PERL_DESTRUCT_LEVEL" in perlhack for more information.
545
546 A more complete garbage collection strategy will be implemented at a
547 future date.
548
549 In the meantime, the best solution is to create a non-recursive con‐
550 tainer class that holds a pointer to the self-referential data struc‐
551 ture. Define a DESTROY method for the containing object's class that
552 manually breaks the circularities in the self-referential structure.
553
555 A kinder, gentler tutorial on object-oriented programming in Perl can
556 be found in perltoot, perlboot and perltooc. You should also check out
557 perlbot for other object tricks, traps, and tips, as well as perlmodlib
558 for some style guides on constructing both modules and classes.
559
560
561
562perl v5.8.8 2006-01-07 PERLOBJ(1)