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