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