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