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