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