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