This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[inseparable changes from patch from perl5.003_07 to perl5.003_08]
[perl5.git] / pod / perlobj.pod
1 =head1 NAME
2
3 perlobj - Perl objects
4
5 =head1 DESCRIPTION
6
7 First of all, you need to understand what references are in Perl.  See
8 L<perlref> for that.  
9
10 Here are three very simple definitions that you should find reassuring.
11
12 =over 4
13
14 =item 1.
15
16 An object is simply a reference that happens to know which class it
17 belongs to.
18
19 =item 2.
20
21 A class is simply a package that happens to provide methods to deal
22 with object references.
23
24 =item 3.
25
26 A method is simply a subroutine that expects an object reference (or
27 a package name, for class methods) as the first argument.
28
29 =back
30
31 We'll cover these points now in more depth.
32
33 =head2 An Object is Simply a Reference
34
35 Unlike say C++, Perl doesn't provide any special syntax for
36 constructors.  A constructor is merely a subroutine that returns a
37 reference to something "blessed" into a class, generally the
38 class that the subroutine is defined in.  Here is a typical
39 constructor:
40
41     package Critter;
42     sub new { bless {} }
43
44 The C<{}> constructs a reference to an anonymous hash containing no 
45 key/value pairs.  The bless() takes that reference and tells the object
46 it references that it's now a Critter, and returns the reference.
47 This is for convenience, since the referenced object itself knows that
48 it has been blessed, and its reference to it could have been returned 
49 directly, like this:
50
51     sub new {
52         my $self = {};
53         bless $self;
54         return $self;
55     }
56
57 In fact, you often see such a thing in more complicated constructors
58 that wish to call methods in the class as part of the construction:
59
60     sub new {
61         my $self = {}
62         bless $self;
63         $self->initialize();
64         return $self;
65     }
66
67 If you care about inheritance (and you should; see
68 L<perlmod/"Modules: Creation, Use and Abuse">),
69 then you want to use the two-arg form of bless
70 so that your constructors may be inherited:
71
72     sub new {
73         my $class = shift;
74         my $self = {};
75         bless $self, $class
76         $self->initialize();
77         return $self;
78     }
79
80 Or if you expect people to call not just C<CLASS-E<gt>new()> but also
81 C<$obj-E<gt>new()>, then use something like this.  The initialize()
82 method used will be of whatever $class we blessed the 
83 object into:
84
85     sub new {
86         my $this = shift;
87         my $class = ref($this) || $this;
88         my $self = {};
89         bless $self, $class
90         $self->initialize();
91         return $self;
92     }
93
94 Within the class package, the methods will typically deal with the
95 reference as an ordinary reference.  Outside the class package,
96 the reference is generally treated as an opaque value that may
97 only be accessed through the class's methods.
98
99 A constructor may re-bless a referenced object currently belonging to
100 another class, but then the new class is responsible for all cleanup
101 later.  The previous blessing is forgotten, as an object may only
102 belong to one class at a time.  (Although of course it's free to 
103 inherit methods from many classes.)
104
105 A clarification:  Perl objects are blessed.  References are not.  Objects
106 know which package they belong to.  References do not.  The bless()
107 function simply uses the reference in order to find the object.  Consider
108 the following example:
109
110     $a = {};
111     $b = $a;
112     bless $a, BLAH;
113     print "\$b is a ", ref($b), "\n";
114
115 This reports $b as being a BLAH, so obviously bless() 
116 operated on the object and not on the reference.
117
118 =head2 A Class is Simply a Package
119
120 Unlike say C++, Perl doesn't provide any special syntax for class
121 definitions.  You just use a package as a class by putting method
122 definitions into the class.
123
124 There is a special array within each package called @ISA which says
125 where else to look for a method if you can't find it in the current
126 package.  This is how Perl implements inheritance.  Each element of the
127 @ISA array is just the name of another package that happens to be a
128 class package.  The classes are searched (depth first) for missing
129 methods in the order that they occur in @ISA.  The classes accessible
130 through @ISA are known as base classes of the current class. 
131
132 If a missing method is found in one of the base classes, it is cached
133 in the current class for efficiency.  Changing @ISA or defining new
134 subroutines invalidates the cache and causes Perl to do the lookup again.
135
136 If a method isn't found, but an AUTOLOAD routine is found, then
137 that is called on behalf of the missing method.
138
139 If neither a method nor an AUTOLOAD routine is found in @ISA, then one
140 last try is made for the method (or an AUTOLOAD routine) in a class
141 called UNIVERSAL.  (Several commonly used methods are automatically
142 supplied in the UNIVERSAL class; see L<"Default UNIVERSAL methods"> for
143 more details.)  If that doesn't work, Perl finally gives up and
144 complains.
145
146 Perl classes only do method inheritance.  Data inheritance is left
147 up to the class itself.  By and large, this is not a problem in Perl,
148 because most classes model the attributes of their object using
149 an anonymous hash, which serves as its own little namespace to be
150 carved up by the various classes that might want to do something
151 with the object.
152
153 =head2 A Method is Simply a Subroutine
154
155 Unlike say C++, Perl doesn't provide any special syntax for method
156 definition.  (It does provide a little syntax for method invocation
157 though.  More on that later.)  A method expects its first argument
158 to be the object or package it is being invoked on.  There are just two
159 types of methods, which we'll call class and instance. 
160 (Sometimes you'll hear these called static and virtual, in honor of
161 the two C++ method types they most closely resemble.)
162
163 A class method expects a class name as the first argument.  It
164 provides functionality for the class as a whole, not for any individual
165 object belonging to the class.  Constructors are typically class
166 methods.  Many class methods simply ignore their first argument, since
167 they already know what package they're in, and don't care what package
168 they were invoked via.  (These aren't necessarily the same, since
169 class methods follow the inheritance tree just like ordinary instance
170 methods.)  Another typical use for class methods is to look up an
171 object by name:
172
173     sub find {
174         my ($class, $name) = @_;
175         $objtable{$name};
176     }
177
178 An instance method expects an object reference as its first argument.
179 Typically it shifts the first argument into a "self" or "this" variable,
180 and then uses that as an ordinary reference.
181
182     sub display {
183         my $self = shift;
184         my @keys = @_ ? @_ : sort keys %$self;
185         foreach $key (@keys) {
186             print "\t$key => $self->{$key}\n";
187         }
188     }
189
190 =head2 Method Invocation
191
192 There are two ways to invoke a method, one of which you're already
193 familiar with, and the other of which will look familiar.  Perl 4
194 already had an "indirect object" syntax that you use when you say
195
196     print STDERR "help!!!\n";
197
198 This same syntax can be used to call either class or instance methods.
199 We'll use the two methods defined above, the class method to lookup
200 an object reference and the instance method to print out its attributes.
201
202     $fred = find Critter "Fred";
203     display $fred 'Height', 'Weight';
204
205 These could be combined into one statement by using a BLOCK in the
206 indirect object slot:
207
208     display {find Critter "Fred"} 'Height', 'Weight';
209
210 For C++ fans, there's also a syntax using -E<gt> notation that does exactly
211 the same thing.  The parentheses are required if there are any arguments.
212
213     $fred = Critter->find("Fred");
214     $fred->display('Height', 'Weight');
215
216 or in one statement,
217
218     Critter->find("Fred")->display('Height', 'Weight');
219
220 There are times when one syntax is more readable, and times when the
221 other syntax is more readable.  The indirect object syntax is less
222 cluttered, but it has the same ambiguity as ordinary list operators.
223 Indirect object method calls are parsed using the same rule as list
224 operators: "If it looks like a function, it is a function".  (Presuming
225 for the moment that you think two words in a row can look like a
226 function name.  C++ programmers seem to think so with some regularity,
227 especially when the first word is "new".)  Thus, the parens of
228
229     new Critter ('Barney', 1.5, 70)
230
231 are assumed to surround ALL the arguments of the method call, regardless
232 of what comes after.  Saying
233
234     new Critter ('Bam' x 2), 1.4, 45
235
236 would be equivalent to
237
238     Critter->new('Bam' x 2), 1.4, 45
239
240 which is unlikely to do what you want.
241
242 There are times when you wish to specify which class's method to use.
243 In this case, you can call your method as an ordinary subroutine
244 call, being sure to pass the requisite first argument explicitly:
245
246     $fred =  MyCritter::find("Critter", "Fred");
247     MyCritter::display($fred, 'Height', 'Weight');
248
249 Note however, that this does not do any inheritance.  If you merely
250 wish to specify that Perl should I<START> looking for a method in a
251 particular package, use an ordinary method call, but qualify the method
252 name with the package like this:
253
254     $fred = Critter->MyCritter::find("Fred");
255     $fred->MyCritter::display('Height', 'Weight');
256
257 If you're trying to control where the method search begins I<and> you're
258 executing in the class itself, then you may use the SUPER pseudoclass,
259 which says to start looking in your base class's @ISA list without having
260 to explicitly name it:
261
262     $self->SUPER::display('Height', 'Weight');
263
264 Please note that the C<SUPER::> construct is I<only> meaningful within the
265 class.
266
267 Sometimes you want to call a method when you don't know the method name
268 ahead of time.  You can use the arrow form, replacing the method name
269 with a simple scalar variable containing the method name:
270
271     $method = $fast ? "findfirst" : "findbest";
272     $fred->$method(@args);
273
274 =head2 Default UNIVERSAL methods
275
276 The C<UNIVERSAL> package automatically contains the following methods that
277 are inherited by all other classes:
278
279 =over 4
280
281 =item isa ( CLASS )
282
283 C<isa> returns I<true> if its object is blessed into a sub-class of C<CLASS>
284
285 C<isa> is also exportable and can be called as a sub with two arguments. This
286 allows the ability to check what a reference points to. Example
287
288     use UNIVERSAL qw(isa);
289
290     if(isa($ref, 'ARRAY')) {
291         ...
292     }
293
294 =item can ( METHOD )
295
296 C<can> checks to see if its object has a method called C<METHOD>,
297 if it does then a reference to the sub is returned, if it does not then
298 I<undef> is returned.
299
300 =item VERSION ( [ VERSION ] )
301
302 C<VERSION> returns the VERSION number of the class (package). If
303 an argument is given then it will check that the current version is not 
304 less that the given argument. This method is normally called as a class
305 method. This method is also called when the C<VERSION> form of C<use> is
306 used.
307
308
309     use A 1.2 qw(some imported subs);
310     
311     A->require_version( 1.2 );
312
313 =item class ()
314
315 C<class> returns the class name of its object.
316
317 =item is_instance ()
318
319 C<is_instance> returns true if its object is an instance of some
320 class, false if its object is the class (package) itself. Example
321
322     A->is_instance();       # False
323     
324     $var = 'A';
325     $var->is_instance();    # False
326     
327     $ref = bless [], 'A';
328     $ref->is_instance();    # True
329
330 =back
331
332 B<NOTE:> C<can> directly uses Perl's internal code for method lookup, and
333 C<isa> uses a very similar method and cache-ing strategy. This may cause
334 strange effects if the Perl code dynamically changes @ISA in any package.
335
336 You may add other methods to the UNIVERSAL class via Perl or XS code.
337
338 =head2 Destructors        
339
340 When the last reference to an object goes away, the object is
341 automatically destroyed.  (This may even be after you exit, if you've
342 stored references in global variables.)  If you want to capture control
343 just before the object is freed, you may define a DESTROY method in
344 your class.  It will automatically be called at the appropriate moment,
345 and you can do any extra cleanup you need to do.
346
347 Perl doesn't do nested destruction for you.  If your constructor
348 reblessed a reference from one of your base classes, your DESTROY may
349 need to call DESTROY for any base classes that need it.  But this only
350 applies to reblessed objects--an object reference that is merely
351 I<CONTAINED> in the current object will be freed and destroyed
352 automatically when the current object is freed.
353
354 =head2 WARNING
355
356 An indirect object is limited to a name, a scalar variable, or a block,
357 because it would have to do too much lookahead otherwise, just like any
358 other postfix dereference in the language.  The left side of -E<gt> is not so
359 limited, because it's an infix operator, not a postfix operator.  
360
361 That means that below, A and B are equivalent to each other, and C and D
362 are equivalent, but AB and CD are different:
363
364     A: method $obref->{"fieldname"} 
365     B: (method $obref)->{"fieldname"}
366     C: $obref->{"fieldname"}->method() 
367     D: method {$obref->{"fieldname"}}
368
369 =head2 Summary
370
371 That's about all there is to it.  Now you just need to go off and buy a
372 book about object-oriented design methodology, and bang your forehead
373 with it for the next six months or so.
374
375 =head2 Two-Phased Garbage Collection
376
377 For most purposes, Perl uses a fast and simple reference-based
378 garbage collection system.  For this reason, there's an extra
379 dereference going on at some level, so if you haven't built
380 your Perl executable using your C compiler's C<-O> flag, performance
381 will suffer.  If you I<have> built Perl with C<cc -O>, then this
382 probably won't matter.
383
384 A more serious concern is that unreachable memory with a non-zero
385 reference count will not normally get freed.  Therefore, this is a bad
386 idea:  
387
388     {
389         my $a;
390         $a = \$a;
391     } 
392
393 Even thought $a I<should> go away, it can't.  When building recursive data
394 structures, you'll have to break the self-reference yourself explicitly
395 if you don't care to leak.  For example, here's a self-referential
396 node such as one might use in a sophisticated tree structure:
397
398     sub new_node {
399         my $self = shift;
400         my $class = ref($self) || $self;
401         my $node = {};
402         $node->{LEFT} = $node->{RIGHT} = $node;
403         $node->{DATA} = [ @_ ];
404         return bless $node => $class;
405     } 
406
407 If you create nodes like that, they (currently) won't go away unless you
408 break their self reference yourself.  (In other words, this is not to be
409 construed as a feature, and you shouldn't depend on it.)
410
411 Almost.
412
413 When an interpreter thread finally shuts down (usually when your program
414 exits), then a rather costly but complete mark-and-sweep style of garbage
415 collection is performed, and everything allocated by that thread gets
416 destroyed.  This is essential to support Perl as an embedded or a
417 multithreadable language.  For example, this program demonstrates Perl's
418 two-phased garbage collection:
419
420     #!/usr/bin/perl 
421     package Subtle;
422
423     sub new {
424         my $test;
425         $test = \$test;
426         warn "CREATING " . \$test;
427         return bless \$test;
428     } 
429
430     sub DESTROY {
431         my $self = shift;
432         warn "DESTROYING $self";
433     } 
434
435     package main;
436
437     warn "starting program";
438     {
439         my $a = Subtle->new;
440         my $b = Subtle->new;
441         $$a = 0;  # break selfref
442         warn "leaving block";
443     } 
444
445     warn "just exited block";
446     warn "time to die...";
447     exit;
448
449 When run as F</tmp/test>, the following output is produced:
450
451     starting program at /tmp/test line 18.
452     CREATING SCALAR(0x8e5b8) at /tmp/test line 7.
453     CREATING SCALAR(0x8e57c) at /tmp/test line 7.
454     leaving block at /tmp/test line 23.
455     DESTROYING Subtle=SCALAR(0x8e5b8) at /tmp/test line 13.
456     just exited block at /tmp/test line 26.
457     time to die... at /tmp/test line 27.
458     DESTROYING Subtle=SCALAR(0x8e57c) during global destruction.
459
460 Notice that "global destruction" bit there?  That's the thread
461 garbage collector reaching the unreachable.  
462
463 Objects are always destructed, even when regular refs aren't and in fact
464 are destructed in a separate pass before ordinary refs just to try to
465 prevent object destructors from using refs that have been themselves
466 destructed.  Plain refs are only garbage collected if the destruct level
467 is greater than 0.  You can test the higher levels of global destruction
468 by setting the PERL_DESTRUCT_LEVEL environment variable, presuming
469 C<-DDEBUGGING> was enabled during perl build time.
470
471 A more complete garbage collection strategy will be implemented
472 at a future date.
473
474 =head1 SEE ALSO
475
476 You should also check out L<perlbot> for other object tricks, traps, and tips, 
477 as well as L<perlmod> for some style guides on constructing both modules
478 and classes.