This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
integrate change#2904 from maint-5.005
[perl5.git] / pod / perlobj.pod
CommitLineData
a0d0e21e
LW
1=head1 NAME
2
3perlobj - Perl objects
4
5=head1 DESCRIPTION
6
5f05dabc 7First of all, you need to understand what references are in Perl.
8See L<perlref> for that. Second, if you still find the following
9reference work too complicated, a tutorial on object-oriented programming
10in Perl can be found in L<perltoot>.
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
53In fact, this might even be preferable, because the C++ programmers won't
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
76In fact, you often see such a thing in more complicated constructors
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
d28ebecd 99Or if you expect people to call not just C<CLASS-E<gt>new()> but also
100C<$obj-E<gt>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
748a9306 118A constructor may re-bless a referenced object currently belonging to
a0d0e21e 119another class, but then the new class is responsible for all cleanup
5f05dabc 120later. The previous blessing is forgotten, as an object may belong
54310121 121to only one class at a time. (Although of course it's free to
5a964f20
TC
122inherit methods from many classes.) If you find yourself having to
123do this, the parent class is probably misbehaving, though.
a0d0e21e
LW
124
125A clarification: Perl objects are blessed. References are not. Objects
126know which package they belong to. References do not. The bless()
5f05dabc 127function uses the reference to find the object. Consider
a0d0e21e
LW
128the following example:
129
130 $a = {};
131 $b = $a;
132 bless $a, BLAH;
133 print "\$b is a ", ref($b), "\n";
134
54310121 135This reports $b as being a BLAH, so obviously bless()
a0d0e21e
LW
136operated on the object and not on the reference.
137
138=head2 A Class is Simply a Package
139
140Unlike say C++, Perl doesn't provide any special syntax for class
5f05dabc 141definitions. You use a package as a class by putting method
a0d0e21e
LW
142definitions into the class.
143
5a964f20 144There is a special array within each package called @ISA, which says
a0d0e21e
LW
145where else to look for a method if you can't find it in the current
146package. This is how Perl implements inheritance. Each element of the
147@ISA array is just the name of another package that happens to be a
148class package. The classes are searched (depth first) for missing
149methods in the order that they occur in @ISA. The classes accessible
54310121 150through @ISA are known as base classes of the current class.
a0d0e21e 151
5a964f20
TC
152All classes implicitly inherit from class C<UNIVERSAL> as their
153last base class. Several commonly used methods are automatically
154supplied in the UNIVERSAL class; see L<"Default UNIVERSAL methods"> for
155more details.
156
a0d0e21e
LW
157If a missing method is found in one of the base classes, it is cached
158in the current class for efficiency. Changing @ISA or defining new
159subroutines invalidates the cache and causes Perl to do the lookup again.
160
5a964f20
TC
161If neither the current class, its named base classes, nor the UNIVERSAL
162class contains the requested method, these three places are searched
163all over again, this time looking for a method named AUTOLOAD(). If an
164AUTOLOAD is found, this method is called on behalf of the missing method,
165setting the package global $AUTOLOAD to be the fully qualified name of
166the method that was intended to be called.
167
168If none of that works, Perl finally gives up and complains.
169
170Perl classes do method inheritance only. Data inheritance is left up
171to the class itself. By and large, this is not a problem in Perl,
172because most classes model the attributes of their object using an
173anonymous hash, which serves as its own little namespace to be carved up
174by the various classes that might want to do something with the object.
175The only problem with this is that you can't sure that you aren't using
176a piece of the hash that isn't already used. A reasonable workaround
177is to prepend your fieldname in the hash with the package name.
178
179 sub bump {
180 my $self = shift;
181 $self->{ __PACKAGE__ . ".count"}++;
182 }
a0d0e21e
LW
183
184=head2 A Method is Simply a Subroutine
185
186Unlike say C++, Perl doesn't provide any special syntax for method
187definition. (It does provide a little syntax for method invocation
188though. More on that later.) A method expects its first argument
5a964f20 189to be the object (reference) or package (string) it is being invoked on. There are just two
54310121 190types of methods, which we'll call class and instance.
55497cff 191(Sometimes you'll hear these called static and virtual, in honor of
192the two C++ method types they most closely resemble.)
a0d0e21e 193
55497cff 194A class method expects a class name as the first argument. It
a0d0e21e 195provides functionality for the class as a whole, not for any individual
55497cff 196object belonging to the class. Constructors are typically class
5f05dabc 197methods. Many class methods simply ignore their first argument, because
a0d0e21e 198they already know what package they're in, and don't care what package
5f05dabc 199they were invoked via. (These aren't necessarily the same, because
55497cff 200class methods follow the inheritance tree just like ordinary instance
201methods.) Another typical use for class methods is to look up an
a0d0e21e
LW
202object by name:
203
204 sub find {
205 my ($class, $name) = @_;
206 $objtable{$name};
207 }
208
55497cff 209An instance method expects an object reference as its first argument.
a0d0e21e
LW
210Typically it shifts the first argument into a "self" or "this" variable,
211and then uses that as an ordinary reference.
212
213 sub display {
214 my $self = shift;
215 my @keys = @_ ? @_ : sort keys %$self;
216 foreach $key (@keys) {
217 print "\t$key => $self->{$key}\n";
218 }
219 }
220
221=head2 Method Invocation
222
223There are two ways to invoke a method, one of which you're already
224familiar with, and the other of which will look familiar. Perl 4
225already had an "indirect object" syntax that you use when you say
226
227 print STDERR "help!!!\n";
228
55497cff 229This same syntax can be used to call either class or instance methods.
230We'll use the two methods defined above, the class method to lookup
231an object reference and the instance method to print out its attributes.
a0d0e21e
LW
232
233 $fred = find Critter "Fred";
234 display $fred 'Height', 'Weight';
235
236These could be combined into one statement by using a BLOCK in the
237indirect object slot:
238
239 display {find Critter "Fred"} 'Height', 'Weight';
240
d28ebecd 241For C++ fans, there's also a syntax using -E<gt> notation that does exactly
a0d0e21e
LW
242the same thing. The parentheses are required if there are any arguments.
243
244 $fred = Critter->find("Fred");
245 $fred->display('Height', 'Weight');
246
247or in one statement,
248
249 Critter->find("Fred")->display('Height', 'Weight');
250
251There are times when one syntax is more readable, and times when the
252other syntax is more readable. The indirect object syntax is less
253cluttered, but it has the same ambiguity as ordinary list operators.
567ce7b1 254Indirect object method calls are usually parsed using the same rule as list
a0d0e21e
LW
255operators: "If it looks like a function, it is a function". (Presuming
256for the moment that you think two words in a row can look like a
257function name. C++ programmers seem to think so with some regularity,
5f05dabc 258especially when the first word is "new".) Thus, the parentheses of
a0d0e21e
LW
259
260 new Critter ('Barney', 1.5, 70)
261
262are assumed to surround ALL the arguments of the method call, regardless
263of what comes after. Saying
264
265 new Critter ('Bam' x 2), 1.4, 45
266
267would be equivalent to
268
269 Critter->new('Bam' x 2), 1.4, 45
270
567ce7b1
SM
271which is unlikely to do what you want. Confusingly, however, this
272rule applies only when the indirect object is a bareword package name,
273not when it's a scalar, a BLOCK, or a C<Package::> qualified package name.
274In those cases, the arguments are parsed in the same way as an
275indirect object list operator like print, so
276
277 new Critter:: ('Bam' x 2), 1.4, 45
278
279is the same as
280
281 Critter::->new(('Bam' x 2), 1.4, 45)
282
283For more reasons why the indirect object syntax is ambiguous, see
284L<"WARNING"> below.
a0d0e21e
LW
285
286There are times when you wish to specify which class's method to use.
287In this case, you can call your method as an ordinary subroutine
288call, being sure to pass the requisite first argument explicitly:
289
290 $fred = MyCritter::find("Critter", "Fred");
291 MyCritter::display($fred, 'Height', 'Weight');
292
5f05dabc 293Note however, that this does not do any inheritance. If you wish
294merely to specify that Perl should I<START> looking for a method in a
a0d0e21e
LW
295particular package, use an ordinary method call, but qualify the method
296name with the package like this:
297
298 $fred = Critter->MyCritter::find("Fred");
299 $fred->MyCritter::display('Height', 'Weight');
300
cb1a09d0 301If you're trying to control where the method search begins I<and> you're
5f05dabc 302executing in the class itself, then you may use the SUPER pseudo class,
cb1a09d0 303which says to start looking in your base class's @ISA list without having
5f05dabc 304to name it explicitly:
cb1a09d0
AD
305
306 $self->SUPER::display('Height', 'Weight');
307
5f05dabc 308Please note that the C<SUPER::> construct is meaningful I<only> within the
cb1a09d0
AD
309class.
310
748a9306
LW
311Sometimes you want to call a method when you don't know the method name
312ahead of time. You can use the arrow form, replacing the method name
313with a simple scalar variable containing the method name:
314
315 $method = $fast ? "findfirst" : "findbest";
316 $fred->$method(@args);
317
a2bdc9a5 318=head2 Default UNIVERSAL methods
319
320The C<UNIVERSAL> package automatically contains the following methods that
321are inherited by all other classes:
322
323=over 4
324
71be2cbc 325=item isa(CLASS)
a2bdc9a5 326
68dc0745 327C<isa> returns I<true> if its object is blessed into a subclass of C<CLASS>
a2bdc9a5 328
329C<isa> is also exportable and can be called as a sub with two arguments. This
330allows the ability to check what a reference points to. Example
331
332 use UNIVERSAL qw(isa);
333
334 if(isa($ref, 'ARRAY')) {
5a964f20 335 #...
a2bdc9a5 336 }
337
71be2cbc 338=item can(METHOD)
a2bdc9a5 339
340C<can> checks to see if its object has a method called C<METHOD>,
341if it does then a reference to the sub is returned, if it does not then
342I<undef> is returned.
343
71be2cbc 344=item VERSION( [NEED] )
760ac839 345
71be2cbc 346C<VERSION> returns the version number of the class (package). If the
347NEED argument is given then it will check that the current version (as
348defined by the $VERSION variable in the given package) not less than
349NEED; it will die if this is not the case. This method is normally
350called as a class method. This method is called automatically by the
351C<VERSION> form of C<use>.
a2bdc9a5 352
a2bdc9a5 353 use A 1.2 qw(some imported subs);
71be2cbc 354 # implies:
355 A->VERSION(1.2);
a2bdc9a5 356
a2bdc9a5 357=back
358
359B<NOTE:> C<can> directly uses Perl's internal code for method lookup, and
360C<isa> uses a very similar method and cache-ing strategy. This may cause
361strange effects if the Perl code dynamically changes @ISA in any package.
362
363You may add other methods to the UNIVERSAL class via Perl or XS code.
71be2cbc 364You do not need to C<use UNIVERSAL> in order to make these methods
365available to your program. This is necessary only if you wish to
366have C<isa> available as a plain subroutine in the current package.
a2bdc9a5 367
54310121 368=head2 Destructors
a0d0e21e
LW
369
370When the last reference to an object goes away, the object is
371automatically destroyed. (This may even be after you exit, if you've
372stored references in global variables.) If you want to capture control
373just before the object is freed, you may define a DESTROY method in
374your class. It will automatically be called at the appropriate moment,
4e8e7886
GS
375and you can do any extra cleanup you need to do. Perl passes a reference
376to the object under destruction as the first (and only) argument. Beware
377that the reference is a read-only value, and cannot be modified by
378manipulating C<$_[0]> within the destructor. The object itself (i.e.
379the thingy the reference points to, namely C<${$_[0]}>, C<@{$_[0]}>,
380C<%{$_[0]}> etc.) is not similarly constrained.
381
382If you arrange to re-bless the reference before the destructor returns,
383perl will again call the DESTROY method for the re-blessed object after
384the current one returns. This can be used for clean delegation of
385object destruction, or for ensuring that destructors in the base classes
386of your choosing get called. Explicitly calling DESTROY is also possible,
387but is usually never needed.
388
389Do not confuse the foregoing with how objects I<CONTAINED> in the current
390one are destroyed. Such objects will be freed and destroyed automatically
391when the current object is freed, provided no other references to them exist
392elsewhere.
a0d0e21e 393
748a9306
LW
394=head2 WARNING
395
5a964f20
TC
396While indirect object syntax may well be appealing to English speakers and
397to C++ programmers, be not seduced! It suffers from two grave problems.
748a9306 398
5a964f20
TC
399The first problem is that an indirect object is limited to a name,
400a scalar variable, or a block, because it would have to do too much
401lookahead otherwise, just like any other postfix dereference in the
402language. (These are the same quirky rules as are used for the filehandle
403slot in functions like C<print> and C<printf>.) This can lead to horribly
404confusing precedence problems, as in these next two lines:
748a9306 405
5a964f20
TC
406 move $obj->{FIELD}; # probably wrong!
407 move $ary[$i]; # probably wrong!
408
409Those actually parse as the very surprising:
410
411 $obj->move->{FIELD}; # Well, lookee here
412 $ary->move->[$i]; # Didn't expect this one, eh?
413
414Rather than what you might have expected:
415
416 $obj->{FIELD}->move(); # You should be so lucky.
417 $ary[$i]->move; # Yeah, sure.
418
419The left side of ``-E<gt>'' is not so limited, because it's an infix operator,
420not a postfix operator.
421
422As if that weren't bad enough, think about this: Perl must guess I<at
423compile time> whether C<name> and C<move> above are functions or methods.
424Usually Perl gets it right, but when it doesn't it, you get a function
425call compiled as a method, or vice versa. This can introduce subtle
426bugs that are hard to unravel. For example, calling a method C<new>
427in indirect notation--as C++ programmers are so wont to do--can
428be miscompiled into a subroutine call if there's already a C<new>
429function in scope. You'd end up calling the current package's C<new>
430as a subroutine, rather than the desired class's method. The compiler
431tries to cheat by remembering bareword C<require>s, but the grief if it
432messes up just isn't worth the years of debugging it would likely take
433you to to track such subtle bugs down.
434
435The infix arrow notation using ``C<-E<gt>>'' doesn't suffer from either
436of these disturbing ambiguities, so we recommend you use it exclusively.
748a9306 437
a0d0e21e
LW
438=head2 Summary
439
5f05dabc 440That's about all there is to it. Now you need just to go off and buy a
a0d0e21e
LW
441book about object-oriented design methodology, and bang your forehead
442with it for the next six months or so.
443
cb1a09d0
AD
444=head2 Two-Phased Garbage Collection
445
446For most purposes, Perl uses a fast and simple reference-based
447garbage collection system. For this reason, there's an extra
448dereference going on at some level, so if you haven't built
449your Perl executable using your C compiler's C<-O> flag, performance
450will suffer. If you I<have> built Perl with C<cc -O>, then this
451probably won't matter.
452
453A more serious concern is that unreachable memory with a non-zero
454reference count will not normally get freed. Therefore, this is a bad
54310121 455idea:
cb1a09d0
AD
456
457 {
458 my $a;
459 $a = \$a;
54310121 460 }
cb1a09d0
AD
461
462Even thought $a I<should> go away, it can't. When building recursive data
463structures, you'll have to break the self-reference yourself explicitly
464if you don't care to leak. For example, here's a self-referential
465node such as one might use in a sophisticated tree structure:
466
467 sub new_node {
468 my $self = shift;
469 my $class = ref($self) || $self;
470 my $node = {};
471 $node->{LEFT} = $node->{RIGHT} = $node;
472 $node->{DATA} = [ @_ ];
473 return bless $node => $class;
54310121 474 }
cb1a09d0
AD
475
476If you create nodes like that, they (currently) won't go away unless you
477break their self reference yourself. (In other words, this is not to be
478construed as a feature, and you shouldn't depend on it.)
479
480Almost.
481
482When an interpreter thread finally shuts down (usually when your program
483exits), then a rather costly but complete mark-and-sweep style of garbage
484collection is performed, and everything allocated by that thread gets
485destroyed. This is essential to support Perl as an embedded or a
54310121 486multithreadable language. For example, this program demonstrates Perl's
cb1a09d0
AD
487two-phased garbage collection:
488
54310121 489 #!/usr/bin/perl
cb1a09d0
AD
490 package Subtle;
491
492 sub new {
493 my $test;
494 $test = \$test;
495 warn "CREATING " . \$test;
496 return bless \$test;
54310121 497 }
cb1a09d0
AD
498
499 sub DESTROY {
500 my $self = shift;
501 warn "DESTROYING $self";
54310121 502 }
cb1a09d0
AD
503
504 package main;
505
506 warn "starting program";
507 {
508 my $a = Subtle->new;
509 my $b = Subtle->new;
510 $$a = 0; # break selfref
511 warn "leaving block";
54310121 512 }
cb1a09d0
AD
513
514 warn "just exited block";
515 warn "time to die...";
516 exit;
517
518When run as F</tmp/test>, the following output is produced:
519
520 starting program at /tmp/test line 18.
521 CREATING SCALAR(0x8e5b8) at /tmp/test line 7.
522 CREATING SCALAR(0x8e57c) at /tmp/test line 7.
523 leaving block at /tmp/test line 23.
524 DESTROYING Subtle=SCALAR(0x8e5b8) at /tmp/test line 13.
525 just exited block at /tmp/test line 26.
526 time to die... at /tmp/test line 27.
527 DESTROYING Subtle=SCALAR(0x8e57c) during global destruction.
528
529Notice that "global destruction" bit there? That's the thread
54310121 530garbage collector reaching the unreachable.
cb1a09d0
AD
531
532Objects are always destructed, even when regular refs aren't and in fact
533are destructed in a separate pass before ordinary refs just to try to
534prevent object destructors from using refs that have been themselves
5f05dabc 535destructed. Plain refs are only garbage-collected if the destruct level
cb1a09d0
AD
536is greater than 0. You can test the higher levels of global destruction
537by setting the PERL_DESTRUCT_LEVEL environment variable, presuming
538C<-DDEBUGGING> was enabled during perl build time.
539
540A more complete garbage collection strategy will be implemented
541at a future date.
542
5a964f20
TC
543In the meantime, the best solution is to create a non-recursive container
544class that holds a pointer to the self-referential data structure.
545Define a DESTROY method for the containing object's class that manually
546breaks the circularities in the self-referential structure.
547
a0d0e21e
LW
548=head1 SEE ALSO
549
54310121 550A kinder, gentler tutorial on object-oriented programming in Perl can
5f05dabc 551be found in L<perltoot>.
54310121 552You should also check out L<perlbot> for other object tricks, traps, and tips,
f102b883 553as well as L<perlmodlib> for some style guides on constructing both modules
cb1a09d0 554and classes.