Commit | Line | Data |
---|---|---|
af36000c DR |
1 | =encoding utf8 |
2 | ||
3 | =for comment | |
4 | Consistent formatting of this file is achieved with: | |
5 | perl ./Porting/podtidy pod/perlobj.pod | |
6 | ||
a0d0e21e | 7 | =head1 NAME |
d74e8afc | 8 | X<object> X<OOP> |
a0d0e21e | 9 | |
af36000c | 10 | perlobj - Perl object reference |
a0d0e21e LW |
11 | |
12 | =head1 DESCRIPTION | |
13 | ||
af36000c DR |
14 | This document provides a reference for Perl's object orientation |
15 | features. If you're looking for an introduction to object-oriented | |
16 | programming in Perl, please see L<perlootut>. | |
17 | ||
18 | In order to understand Perl objects, you first need to understand | |
19 | references in Perl. See L<perlref> for details. | |
a0d0e21e | 20 | |
af36000c DR |
21 | This document describes all of Perl's OO features from the ground up. |
22 | If you're just looking to write some object-oriented code of your own, | |
23 | you are probably better served by using one of the object systems from | |
24 | CPAN described in L<perlootut>. | |
25 | ||
26 | If you're looking to write your own object system, or you need to | |
27 | maintain code which implements objects from scratch then this document | |
28 | will help you understand exactly how Perl does object orientation. | |
29 | ||
30 | There are a few basic principles which define object oriented Perl: | |
a0d0e21e LW |
31 | |
32 | =over 4 | |
33 | ||
34 | =item 1. | |
35 | ||
af36000c | 36 | An object is simply a reference that knows which class it belongs to. |
a0d0e21e LW |
37 | |
38 | =item 2. | |
39 | ||
af36000c DR |
40 | A class is simply a package. A class provides methods that expect to |
41 | operate on objects. | |
a0d0e21e LW |
42 | |
43 | =item 3. | |
44 | ||
af36000c DR |
45 | A method is simply a subroutine that expects an object reference (or a |
46 | package name, for class methods) as the first argument. | |
a0d0e21e LW |
47 | |
48 | =back | |
49 | ||
af36000c | 50 | Let's look at each of these principles in depth. |
a0d0e21e LW |
51 | |
52 | =head2 An Object is Simply a Reference | |
d74e8afc | 53 | X<object> X<bless> X<constructor> X<new> |
a0d0e21e | 54 | |
af36000c DR |
55 | Unlike many other languages which support object orientation, Perl does |
56 | not provide any special syntax for constructing an object. A | |
57 | constructor is just a subroutine that returns a reference which has | |
58 | been "blessed" into a class. | |
a0d0e21e | 59 | |
af36000c | 60 | Here is a simple constructor: |
a0d0e21e | 61 | |
af36000c | 62 | package File; |
5a964f20 | 63 | |
af36000c DR |
64 | sub new { |
65 | my $class = shift; | |
a0d0e21e | 66 | |
af36000c DR |
67 | return bless {}, $class; |
68 | } | |
5a964f20 | 69 | |
af36000c DR |
70 | The name C<new> isn't special. We could name our constructor something |
71 | else: | |
5a964f20 | 72 | |
af36000c DR |
73 | sub load { |
74 | my $class = shift; | |
75 | ||
76 | return bless {}, $class; | |
77 | } | |
78 | ||
79 | The modern convention for OO modules is to use C<new> as the | |
80 | constructor, but you are free to use the name if that works best for | |
81 | your class. | |
82 | ||
83 | The C<{}> code creates an empty anonymous hash reference. The C<bless> | |
84 | function takes that reference and associates it with the class in | |
85 | C<$class>. In the simplest case, the C<$class> variable will end up | |
86 | containing the string "Critter". | |
87 | ||
88 | We can also call bless on a named variable: | |
89 | ||
90 | sub new { | |
91 | my $class = shift; | |
92 | ||
93 | my $self = {}; | |
94 | bless $self, $class; | |
95 | ||
96 | return $self; | |
97 | } | |
98 | ||
99 | Once we've blessed C<$self> we can start calling methods on it. This is | |
100 | useful if you want to break out object initialization to its own | |
101 | method: | |
102 | ||
103 | sub new { | |
104 | my $class = shift; | |
105 | ||
106 | my $self = {}; | |
107 | bless $self, $class; | |
108 | ||
109 | $self->_initialize(); | |
110 | ||
111 | return $self; | |
112 | } | |
ed850460 | 113 | |
af36000c DR |
114 | Since the object is also a hash reference, you can treat it as one, |
115 | using it store data associated with the object. Typically, code inside | |
116 | the class can treat the hash as reference, while code outside the class | |
117 | should always treat the object as opaque. This is called | |
118 | B<encapsulation>. Encapsulation means that the user of an object does | |
119 | not have to know how it is implemented. The user simply calls | |
120 | documented methods on the object. | |
ed850460 | 121 | |
af36000c DR |
122 | =head2 A Class is Simply a Package |
123 | X<class> X<package> X<@ISA> X<inheritance> | |
ed850460 | 124 | |
af36000c DR |
125 | Perl does not provide any special syntax for class definitions. A |
126 | package is simply a namespace containing variables and subroutines. The | |
127 | only difference is that in a class, the subroutines expect an object or | |
128 | class as the first argument. | |
129 | ||
130 | Each package contains a special array reference called C<@ISA>. The | |
131 | C<@ISA> array contains a list of that class's parent classes, if any. | |
132 | This array is examined when Perl does method resolution, which we will | |
133 | cover later. | |
134 | ||
135 | It is possible to manually set C<@ISA>, and you may see this in older | |
136 | Perl code. For new code, we recommend that you use the L<parent> pragma | |
137 | to declare your parents. This pragma will take care of setting C<@ISA>. | |
138 | It will also load the parent classes and make sure that the package | |
139 | doesn't inherit from itself. | |
140 | ||
141 | All classes inherit from the L<UNIVERSAL> class implicitly. The | |
142 | L<UNIVERSAL> class is implemented by the Perl core, and provides | |
143 | several default methods, such as C<isa()>, C<can()>, and C<VERSION()>. | |
144 | X<UNIVERSAL> X<base class> X<class, base> | |
5a964f20 | 145 | |
af36000c DR |
146 | Perl I<only> provides method inheritance as a built-in feature. |
147 | Attribute inheritance is left up the class to implement. See the | |
148 | L</Attributes> section for details. | |
a0d0e21e LW |
149 | |
150 | =head2 A Method is Simply a Subroutine | |
d74e8afc | 151 | X<method> |
a0d0e21e | 152 | |
af36000c DR |
153 | Perl does not provide any special syntax for defining a method. A |
154 | method is simply a regular subroutine, and is declared with C<sub>. | |
155 | What makes a method special is that it expects to receive either an | |
156 | object or a class name as its first argument. | |
157 | ||
158 | Perl I<does> provide special syntax for method invocation, the C<< -> | |
159 | >> operator. We will cover this in more detail later. | |
160 | ||
161 | Most methods you write will expect to operate on objects: | |
162 | ||
163 | sub save { | |
164 | my $self = shift; | |
165 | ||
166 | open my $fh, '>', $self->path() | |
167 | or die $!; | |
168 | print {$fh} $self->data() | |
169 | or die $!; | |
170 | close $fh | |
171 | or die $!; | |
172 | } | |
a0d0e21e LW |
173 | |
174 | =head2 Method Invocation | |
d74e8afc | 175 | X<invocation> X<method> X<arrow> X<< -> >> |
a0d0e21e | 176 | |
af36000c DR |
177 | Calling a method on an object is written as C<< $object->method >>. The |
178 | left hand side of the method invocation (or arrow) operator is the | |
179 | object (or class name), and the right hand side is the method name. | |
a0d0e21e | 180 | |
af36000c DR |
181 | my $pod = File->new( 'perlobj.pod', $data ); |
182 | $pod->save(); | |
a0d0e21e | 183 | |
af36000c DR |
184 | The C<< -> >> operator is also used when dereferencing a reference. |
185 | It's the same operator, but it has two different uses. | |
a0d0e21e | 186 | |
af36000c DR |
187 | When you call a method, the thing on the left side of the arrow is |
188 | passed as the first argument to the method. That means when we call C<< | |
189 | Critter->new() >>, the C<new()> method receives the string C<"Critter"> | |
190 | as its first argument. When we call C<< $fred->speak() >>, the C<$fred> | |
191 | object is passed as the first argument to C<speak()> | |
a0d0e21e | 192 | |
af36000c DR |
193 | Perl knows what package the method is in by looking at the left side of |
194 | the arrow. If the left hand side is a package name, it looks for the | |
195 | method in the package. If the left hand side is an object, then Perl | |
196 | can tell what class that object has been blessed into. | |
a0d0e21e | 197 | |
af36000c DR |
198 | If the left hand side is neither a package name nor an object, then the |
199 | method call will cause an error, but see the section on L</Method Call | |
200 | Variations> for more nuances. | |
a0d0e21e | 201 | |
af36000c DR |
202 | =head2 Inheritance |
203 | X<inheritance> | |
a0d0e21e | 204 | |
af36000c DR |
205 | We already talked about the special C<@ISA> array and the L<parent> |
206 | pragma. | |
a0d0e21e | 207 | |
af36000c DR |
208 | When a class inherits from another class, any methods defined in the |
209 | parent class are available in the child class. If you attempt to call a | |
210 | method on an object that isn't defined in its own class, Perl will also | |
211 | look for that method in any parent classes it may have. | |
a0d0e21e | 212 | |
af36000c DR |
213 | package File::MP3; |
214 | use parent 'File'; # sets @File::MP3::ISA = ('File'); | |
215 | ||
216 | my $mp3 = File::MP3->new( 'Andvari.mp3', $data ); | |
217 | $mp3->save(); | |
218 | ||
219 | Since we didn't define a C<save()> method in the C<File::MP3> class, | |
220 | Perl will look at the C<File::MP3> class's parent classes to find the | |
221 | C<save()> method. If Perl could not find a C<save()> method anywhere in | |
222 | the inheritance hierarchy, it would die. | |
223 | ||
224 | In this case, it finds it in the C<File> class. Note that the object | |
225 | passed to C<save()> in this case is still a C<File::MP3> object, even | |
226 | though the method is found in the C<File> class. | |
a0d0e21e | 227 | |
af36000c DR |
228 | We can override a parent's method in a child class. When we do so, we |
229 | can still call the parent class's method with the C<SUPER> | |
230 | pseudo-class. | |
a0d0e21e | 231 | |
af36000c DR |
232 | sub save { |
233 | my $self = shift; | |
a0d0e21e | 234 | |
af36000c DR |
235 | say 'Prepare to rock'; |
236 | $self->SUPER::save(); | |
237 | } | |
238 | ||
239 | The C<SUPER> modifier can I<only> be used for method calls. You can't | |
240 | use it for regular subroutine calls: | |
241 | ||
242 | # XXX - This will not work! | |
243 | SUPER::save($thing); | |
244 | # This won't work either! | |
245 | SUPER->save($thing); | |
246 | ||
247 | =head3 How SUPER is Resolved | |
d74e8afc | 248 | X<SUPER> |
029f3b44 | 249 | |
af36000c DR |
250 | The C<SUPER> pseudo-class is resolved from the package where the call |
251 | is made. It is I<not> resolved based on the object's class. This is | |
252 | important, because it lets an inheritance hierarchy several levels deep | |
253 | all call their parent methods. | |
254 | ||
255 | package A; | |
256 | ||
257 | sub new { | |
258 | return bless {}, shift; | |
259 | } | |
260 | ||
261 | sub speak { | |
262 | my $self = shift; | |
263 | ||
264 | $self->SUPER::speak(); | |
265 | ||
266 | say 'A'; | |
267 | } | |
268 | ||
269 | package B; | |
270 | ||
271 | use parent 'A'; | |
272 | ||
273 | sub speak { | |
274 | my $self = shift; | |
029f3b44 | 275 | |
af36000c | 276 | $self->SUPER::speak(); |
a0d0e21e | 277 | |
af36000c DR |
278 | say 'B'; |
279 | } | |
a0d0e21e | 280 | |
af36000c | 281 | package C; |
cb1a09d0 | 282 | |
af36000c | 283 | use parent 'B'; |
cb1a09d0 | 284 | |
af36000c DR |
285 | sub speak { |
286 | my $self = shift; | |
d9693f5a | 287 | |
af36000c | 288 | $self->SUPER::speak(); |
e947c198 | 289 | |
af36000c DR |
290 | say 'C'; |
291 | } | |
e947c198 | 292 | |
af36000c DR |
293 | my $c = C->new(); |
294 | $c->speak(); | |
e947c198 | 295 | |
af36000c | 296 | In this example, we will get the following outupt: |
cb1a09d0 | 297 | |
af36000c DR |
298 | A |
299 | B | |
300 | C | |
748a9306 | 301 | |
af36000c DR |
302 | This demonstrates how C<SUPER> is resolved. Even though the object is |
303 | blessed into the C<C> class, the C<speak()> method in the C<B> class | |
304 | can still call C<SUPER::speak()>. | |
19799a22 | 305 | |
af36000c DR |
306 | There are cases where this package-based resolution can be a problem. |
307 | If you copy a subroutine from one package to another, C<SUPER> | |
308 | resolution will be done based on the original package. | |
19799a22 | 309 | |
af36000c DR |
310 | =head3 Multiple Inheritance |
311 | X<multiple inheritance> | |
19799a22 | 312 | |
af36000c DR |
313 | Multiple inheritance often indicates a design problem, but Perl always |
314 | give you enough rope to hang yourself with. | |
19799a22 | 315 | |
af36000c DR |
316 | To declare multiple parents, you simply need to pass multiple class |
317 | names to C<use parent>: | |
5d9f8747 | 318 | |
af36000c | 319 | package MultiChild; |
5d9f8747 | 320 | |
af36000c | 321 | use parent 'Parent1', 'Parent2'; |
19799a22 | 322 | |
af36000c DR |
323 | =head3 Method Resolution Order |
324 | X<method resolution order> X<mro> | |
325 | ||
326 | Method resolution order only matters in the case of multiple | |
327 | inheritance. In the case of single inheritance, Perl simply looks up | |
328 | the inheritance chain to find a method: | |
329 | ||
330 | Grandparent | |
331 | | | |
332 | Parent | |
333 | | | |
334 | Child | |
335 | ||
336 | If we call a method on a C<Child> object and that method is not defined | |
337 | in the C<Child> class, Perl will look for that method. in the C<Parent> | |
338 | class and then the C<Grandparent> class. | |
339 | ||
340 | If Perl cannot find the method in any of these classes, it will die | |
341 | with an error message. | |
342 | ||
343 | When a class has multiple parents, the method lookup order becomes more | |
344 | complicated. | |
345 | ||
346 | By default, Perl does a depth-first left-to-right search for a method. | |
347 | That means it starts with the first parent in the C<@ISA> array, and | |
348 | then searches all of its parents and so on. If it fails to find the | |
349 | method, it then goes to the next parent in the original class's C<@ISA> | |
350 | array and searches from there. | |
351 | ||
352 | PaternalGrandparent MaternalGrandparent | |
353 | \ / | |
354 | Father Mother | |
355 | \ / | |
356 | Child | |
357 | ||
358 | So given the diagram above, Perl will search C<Child>, C<Father>, | |
359 | C<PaternalGrandparent>, C<Mother>, and finally C<MaternalGrandparent> | |
360 | ||
361 | It is possible to ask for a different method resolution order with the | |
362 | L<mro> pragma. | |
363 | ||
364 | package Child; | |
365 | ||
366 | use mro 'c3'; | |
367 | use parent 'Father', 'Mother'; | |
368 | ||
369 | This pragma lets you switch to the "C3" resolution order. In simple | |
370 | terms, this is a breadth-first order, so Perl will search C<Child>, | |
371 | C<Father>, C<Mother>, C<PaternalGrandparent>, and finally | |
372 | C<MaternalGrandparent>. | |
373 | ||
374 | The C3 order also lets you call methods in sibling classes with the | |
375 | C<next> pseudo-class. See the L<mro> documentation for more details on | |
376 | this feature. | |
377 | ||
378 | =head3 Method Resolution Caching | |
379 | ||
380 | When Perl searches for a method, it caches the lookup so that future | |
381 | calls to the method do not need to search for it again. Changing a | |
382 | class's parent class or adding subroutines to a class will invalidate | |
383 | the cache for that class. | |
384 | ||
385 | The L<mro> pragma provides some functions for manipulating the method | |
386 | cache directly. | |
387 | ||
388 | =head2 Writing Constructors | |
389 | X<constructor> | |
390 | ||
391 | As we mentioned earlier, Perl provides no special constructor syntax. | |
392 | This means that a class must implement its own constructor. A | |
393 | constructor is simply a class method that returns a new object. | |
394 | ||
395 | The constructor can also accept additional parameters that define the | |
396 | object. Let's write a real constructor for the C<File> class we used | |
397 | earlier: | |
398 | ||
399 | package File; | |
400 | ||
401 | sub new { | |
402 | my $class = shift; | |
403 | my ( $path, $data ) = @_; | |
404 | ||
405 | my $self = bless { | |
406 | path => $path, | |
407 | data => $data, | |
408 | }, $class; | |
409 | ||
410 | return $self; | |
411 | } | |
412 | ||
413 | As you can see, we've stored the path and file data in the object | |
414 | itself. Remember, under the hood, this object is still just a hash | |
415 | reference. Later, we'll write accessors to manipulate this data. | |
416 | ||
417 | For our File::MP3 class, we can check to make sure that the path we're | |
418 | given ends with ".mp3": | |
419 | ||
420 | package File::MP3; | |
421 | ||
422 | sub new { | |
423 | my $class = shift; | |
424 | my ( $path, $data ) = @_; | |
425 | ||
426 | die "You cannot create a File::MP3 without an mp3 extension\n" | |
427 | unless $path =~ /\.mp3\z/; | |
428 | ||
429 | return $class->SUPER::new(@_); | |
430 | } | |
431 | ||
432 | This constructor lets its parent class do the actual object | |
433 | construction. | |
434 | ||
435 | =head2 Writing Accessors | |
436 | X<accessor> | |
437 | ||
438 | As with constructors, Perl provides no special accessor declaration | |
439 | syntax, so classes must write them by hand. There are two common types | |
440 | of accessors, read-only and read-write. | |
441 | ||
442 | A simple read-only accessor simply gets the value of a single | |
443 | attribute: | |
444 | ||
445 | sub path { | |
446 | my $self = shift; | |
447 | ||
448 | return $self->{path}; | |
449 | } | |
450 | ||
451 | A read-write accessor will allow the caller to set the value as well as | |
452 | get it: | |
453 | ||
454 | sub path { | |
455 | my $self = shift; | |
456 | ||
457 | if (@_) { | |
458 | $self->{path} = shift; | |
459 | } | |
460 | ||
461 | return $self->{path}; | |
462 | } | |
463 | ||
464 | =head2 An Aside About Smarter and Safer Code | |
465 | ||
466 | Our constructor and accessors are not very smart. They don't check that | |
467 | a C<$path> is defined, nor do they check that a C<$path> is a valid | |
468 | filesystem path. | |
469 | ||
470 | Doing these checks by hand can quickly become tedious. Writing a bunch | |
471 | of accessors by hand is also incredibly tedioud. There are a lot of | |
472 | modules on CPAN that can help you write safer and more concise code, | |
473 | including the modules we recommend in L<perlootut>. | |
474 | ||
475 | =head2 Method Call Variations | |
476 | X<method> | |
19799a22 | 477 | |
af36000c DR |
478 | Perl supports several other ways to call methods besides the typical |
479 | C<< $object->method() >> pattern we've seen so far. | |
19799a22 | 480 | |
af36000c | 481 | =head3 Method Names as Strings |
19799a22 | 482 | |
af36000c DR |
483 | Perl lets you use a scalar variable containing a string as a method |
484 | name: | |
19799a22 | 485 | |
af36000c | 486 | my $file = File->new( $path, $data ); |
19799a22 | 487 | |
af36000c DR |
488 | my $method = 'save'; |
489 | $file->$method(); | |
19799a22 | 490 | |
af36000c DR |
491 | This works exactly like calling C<< $file->save() >>. This can be very |
492 | useful for writing dynamic code. For example, it allows you to pass a | |
493 | method name to be called as a parameter to another method. | |
5d9f8747 | 494 | |
af36000c | 495 | =head3 Class Names as Strings |
748a9306 | 496 | |
af36000c DR |
497 | Perl also lets you use a scalar containing a string as a class name: |
498 | ||
499 | my $class = 'File'; | |
500 | ||
501 | my $file = $class->new( $path, $data ); | |
502 | ||
503 | Again, this allows for very dynamic code. | |
504 | ||
505 | =head3 Subroutine References as Methods | |
506 | ||
507 | You can also call subroutine reference as a method: | |
508 | ||
509 | my $sub = sub { | |
510 | my $self = shift; | |
511 | ||
512 | $self->save(); | |
513 | }; | |
514 | ||
515 | $file->$sub(); | |
516 | ||
517 | This is exactly equivalent to writing C<< $sub->($file) >>. You may see | |
518 | this idiom in the wild combined with a call to C<can>: | |
519 | ||
520 | if ( my $meth = $object->can('foo') ) { | |
521 | $object->$meth(); | |
522 | } | |
523 | ||
524 | =head2 Invoking Class Methods | |
525 | X<invocation> | |
526 | ||
527 | Because Perl allows you to use barewords for package names and | |
528 | subroutine names, it can sometimes guess wrong about what you intend a | |
529 | bareword to be. The construct C<< Class->new() >> can be interpreted as | |
530 | C<< Class()->new() >>. In English, that reads as "call a subroutine | |
531 | named Class(), then call new() as a method on the return value". | |
532 | ||
533 | You can force Perl to interpret this as a class method call in two | |
534 | ways. First, you can append a C<::> to the class name: | |
535 | ||
536 | Class::->new() | |
537 | ||
538 | Perl will always interpret this as a method call. You can also quote | |
539 | the class name: | |
540 | ||
541 | 'Class'->new() | |
542 | ||
543 | Of course, if the class name is in a scalar Perl will do the right | |
544 | thing as well: | |
545 | ||
546 | my $class = 'Class'; | |
547 | $class->new(); | |
548 | ||
549 | =head3 Indirect Object Syntax | |
550 | X<indirect object> | |
551 | ||
552 | B<Outside of the file handle case, use of this syntax is discouraged, | |
553 | as it can confuse the Perl interpreter. See below for more details.> | |
554 | ||
555 | Perl suports another method invocation syntax called "indirect object" | |
556 | notation. | |
557 | ||
558 | This notation is quite common when used with file handles: | |
559 | ||
560 | print $fh $data; | |
561 | ||
562 | This is really like calling C<< $fh->print($data) >>. This syntax is | |
563 | called "indirect" because the method comes before the object it is | |
564 | being invoked on. | |
565 | ||
566 | This syntax can be used with any class or object method: | |
567 | ||
568 | my $file = new File $path, $data; | |
569 | save $file; | |
570 | ||
571 | We recommend that you avoid this syntax, for several reasons. | |
572 | ||
573 | First, it can be confusing to read. In the above example, it's not | |
574 | clear if C<save> is a method or simply a subroutine that expects a file | |
575 | object as its first argument. | |
576 | ||
577 | When used with class methods, the problem is even worse. Because Perl | |
578 | allows subroutine names to be written as barewords, Perl has to guess | |
579 | whether the bareword after the method is a class name or subroutine | |
580 | name. In other words, Perl can resolve the syntax as either C<< | |
581 | File->new( $path, $data ) >> B<or> C<< new( File( $path, $data ) ) >>. | |
582 | ||
583 | To parse this code, Perl uses a heuristic based on what package names | |
584 | it has seen, what subroutines exist in the current package, and what | |
585 | barewords it has seen previously. Needless to say, heuristics can | |
586 | produce very surprising results! | |
587 | ||
588 | Older documentation (and some CPAN modules) encouraged this syntax, | |
589 | particularly for constructors, so you may still find it in the wild. | |
590 | However, we encourage you to avoid using it in new code. | |
591 | ||
592 | =head2 C<bless>, C<blessed>, and C<ref> | |
593 | ||
594 | As we saw earlier, an object is simply a reference that has been | |
595 | blessed into a class with the C<bless> function. The C<bless> function | |
596 | has can take either one or two arguments: | |
597 | ||
598 | my $object = bless {}, $class; | |
599 | my $object = bless {}; | |
600 | ||
601 | In the first form, the anonymous hash reference is being blessed into | |
602 | the class in C<$class>. In the second form, the reference is blessed | |
603 | into the current package. | |
604 | ||
605 | The second form is discouraged, because it breaks the ability of a | |
606 | subclass to reuse the parent's constructor, but you may still run | |
607 | across it in existing code. | |
608 | ||
609 | If you want to know whether a particular scalar is an object, you can | |
610 | use the C<blessed> function exported by L<Scalar::Util>, which is | |
611 | shipped with the Perl core. | |
612 | ||
613 | use Scalar::Util 'blessed'; | |
614 | ||
615 | if ( blessed($thing) ) { ... } | |
616 | ||
617 | If the C<$thing> has been blessed, then this function returns the name | |
618 | of the package the object has been blessed into. Note that the example | |
619 | above will return false if C<$thing> has been blessed into a class | |
620 | named "0". If the C<$thing> is not a blessed reference, the C<blessed> | |
621 | function returns false. | |
622 | ||
623 | Similarly, Perl's built in C<ref> function treats a blessed reference | |
624 | specially. If you call C<ref($thing)> and C<$thing> is an object, it | |
625 | will return the name of the class that the object has been blessed | |
626 | into. | |
627 | ||
628 | If you simply want to check that a variable contains an object, we | |
629 | recommend that you use C<blessed>, since C<ref> returns true values for | |
630 | all references, not just objects. | |
631 | ||
632 | =head2 The UNIVERSAL Class | |
d74e8afc | 633 | X<UNIVERSAL> |
a2bdc9a5 | 634 | |
af36000c DR |
635 | All classes automatically inherit from the L<UNIVERSAL> class, which is |
636 | built in to the Perl core. This class provides a number of methods, all | |
637 | of which can be called on either a class or an object. You can also | |
638 | choose to override some of these methods in your class. If you do so, | |
639 | we recommend that you follow the built in semantics described below. | |
a2bdc9a5 | 640 | |
641 | =over 4 | |
642 | ||
af36000c | 643 | =item isa($class) |
d74e8afc | 644 | X<isa> |
a2bdc9a5 | 645 | |
af36000c DR |
646 | The C<isa> method returns I<true> if the object is a member of the |
647 | class in C<$class>, or a member of a subclass of C<$class>. | |
a2bdc9a5 | 648 | |
af36000c | 649 | =item DOES($role) |
003db2bd | 650 | X<DOES> |
bcb8f0e8 | 651 | |
af36000c DR |
652 | The C<DOES> method returns I<true> if its object claims to perform the |
653 | role C<$role>. By default, this is equivalent to C<isa>. This method is | |
654 | provided for use by object system extensions that implement roles, like | |
655 | C<Moose> and C<Role::Tiny>. | |
bcb8f0e8 | 656 | |
af36000c | 657 | =item can($method) |
d74e8afc | 658 | X<can> |
a2bdc9a5 | 659 | |
af36000c DR |
660 | The C<can> method checks to see if its object has a method called |
661 | C<$method>. If it does, then a reference to the subroutine is returned. | |
662 | If it does not then C<undef> is returned. | |
663 | ||
664 | This will return true if the object's class or any of it's parent | |
665 | classes contain C<$method>. | |
b32b0a5d | 666 | |
af36000c DR |
667 | If your class responds to method calls via C<AUTOLOAD>, you may want to |
668 | overload C<can> to respond true for methods which C<AUTOLOAD> handles. | |
669 | ||
670 | =item VERSION($need) | |
d74e8afc | 671 | X<VERSION> |
760ac839 | 672 | |
af36000c DR |
673 | The C<VERSION> method returns the version number of the class |
674 | (package). | |
675 | ||
676 | If the C<$need> argument is given then it will check that the current | |
677 | version (as defined by the $VERSION variable in the package) is greater | |
678 | than or equal to C<$need>; it will die if this is not the case. This | |
679 | method is called automatically by the C<VERSION> form of C<use>. | |
a2bdc9a5 | 680 | |
003db2bd | 681 | use Package 1.2 qw(some imported subs); |
71be2cbc | 682 | # implies: |
003db2bd | 683 | Package->VERSION(1.2); |
a2bdc9a5 | 684 | |
af36000c DR |
685 | We recommend that you use this method to access another package's |
686 | version, rather than looking directly at C<$Package::VERSION>. The | |
687 | package you are looking at could have overridden the C<VERSION> method. | |
688 | ||
689 | We also recommend using this method to check whether a module has a | |
690 | sufficient version. The internal implementation uses the L<version> | |
691 | module to make sure that different types of version numbers are | |
692 | compared correctly. | |
693 | ||
a2bdc9a5 | 694 | =back |
695 | ||
af36000c DR |
696 | =head2 AUTOLOAD |
697 | X<AUTOLOAD> | |
698 | ||
699 | If you call a method that doesn't exist in a class, Perl will throw an | |
700 | error. However, if that class or any of its parent classes defined an | |
701 | C<AUTOLOAD> method, that method will be called instead. | |
702 | ||
703 | This is called as a regular method, and the caller will not know the | |
704 | difference. Whatever value your C<AUTOLOAD> method returns is given to | |
705 | the caller. | |
706 | ||
707 | The fully qualified method name that was called is available in the | |
708 | C<$AUTOLOAD> package global for your class. Since this is a global, if | |
709 | you want to refer to do it without a package name prefix, you need to | |
710 | declare it. | |
711 | ||
712 | # XXX - this is a terrible way to implement accessors, but it makes for a | |
713 | # simple example. | |
714 | our $AUTOLOAD; | |
715 | sub AUTOLOAD { | |
716 | my $self = shift; | |
717 | ||
718 | ( my $called = $AUTOLOAD ) =~ s/.*:://; | |
719 | ||
720 | return if $called eq 'DESTROY'; | |
721 | ||
722 | die "No such attribute: $called" | |
723 | unless exists $self->{$called}; | |
724 | ||
725 | return $self->{$called}; | |
726 | } | |
727 | ||
728 | Without the C<our $AUTOLOAD> declaration, this code will not compile | |
729 | under the L<strict> pragma. | |
730 | ||
731 | As the comment says, this is not a good way to implement accessors. | |
732 | It's slow and too clever by far. See L<perlootut> for recommendations | |
733 | on OO coding in Perl. | |
734 | ||
735 | If your class does have an C<AUTOLOAD> method, we strongly recommend | |
736 | that you override C<can> in your class as well. Your overridden C<can> | |
737 | method should return a subroutine reference for any method that your | |
738 | C<AUTOLOAD> responds to. | |
739 | ||
54310121 | 740 | =head2 Destructors |
d74e8afc | 741 | X<destructor> X<DESTROY> |
a0d0e21e | 742 | |
af36000c DR |
743 | When the last refernce to an object goes away, the object is destroyed. |
744 | If you only have one reference to an object stored in a lexical scalar, | |
745 | the object is destroyed when that lexical goes out of scope. If you | |
746 | store the object in a global, that object may not go out of scope until | |
747 | the program exits. | |
748 | ||
749 | If you want to do something when the object is destroyed, you can | |
750 | defined a C<DESTROY> method in your class. This method will always be | |
751 | called by Perl at the appropriate time. | |
752 | ||
753 | This is called just like any other method, with the object as the first | |
754 | argument. It does not receive any additional arguments. | |
755 | ||
756 | Because C<DESTROY> methods can be called at any time, you should | |
757 | localize any global variables you might update in your C<DESTROY>. In | |
758 | particular, if you use C<eval {}> you should localize C<$@>, and if you | |
759 | use C<system> or backticks, you should localize C<$?>. | |
760 | ||
761 | As we saw in the C<AUTOLOAD> example, if you define an C<AUTOLOAD> | |
762 | method, this will be called for the C<DESTROY> method, so you need to | |
763 | handle this case in your C<AUTOLOAD>. | |
764 | ||
765 | The order in which objects are destroyed when the program exits is | |
766 | unpredictable. This means that any objects contained by your object may | |
767 | already have been destroyed. This means you should check that they are | |
768 | defined before calling methods on them: | |
769 | ||
770 | sub DESTROY { | |
771 | my $self = shift; | |
772 | ||
773 | $self->{handle}->close() if $self->{handle}; | |
774 | } | |
775 | ||
776 | You can use the C<${^GLOBAL_PHASE}> variable to detect if you are | |
777 | currently in the program exit phase: | |
778 | ||
779 | sub DESTROY { | |
780 | my $self = shift; | |
781 | ||
782 | return if ${^GLOBAL_PHASE} eq 'DESTRUCT'; | |
783 | ||
784 | $self->{handle}->close(); | |
785 | } | |
786 | ||
787 | Note that this variable was added in Perl 5.14.0. If you want to detect | |
788 | program exit on older versions of Perl, you can use the | |
789 | C<Devel::GlobalDestruction> module on CPAN. | |
790 | ||
791 | =head2 Non-Hashref Objects | |
792 | ||
793 | All the examples so far have shown objects based on a blessed hash | |
794 | reference. However, it's possible to bless any type of reference, | |
795 | including scalar refs, glob refs, and code refs. You may see this sort | |
796 | of thing when looking at code in the wild. | |
797 | ||
798 | Here's an example of a module as a blessed scalar: | |
799 | ||
800 | package Time; | |
801 | ||
e011bc34 DR |
802 | use strict; |
803 | use warnings; | |
804 | ||
af36000c DR |
805 | sub new { |
806 | my $class = shift; | |
807 | ||
808 | my $time = time; | |
809 | return bless \$time, $class; | |
810 | } | |
811 | ||
812 | sub epoch { | |
813 | my $self = shift; | |
814 | return ${ $self }; | |
815 | } | |
816 | ||
817 | my $time = Time->new(); | |
818 | print $time->epoch(); | |
819 | ||
820 | =head2 Inside-Out objects | |
821 | ||
e011bc34 DR |
822 | In the past, the Perl community experimented with a technique called |
823 | "inside-out objects". An inside-out object stores its data in a lexical | |
824 | class variable, indexed on a unique property of the object, such as its | |
825 | memory address, rather than in the object itself. | |
af36000c | 826 | |
e011bc34 DR |
827 | This technique was popular for a while (and was recommended in Damian |
828 | Conway's I<Perl Best Practices>), but never achieved wide adoption due | |
829 | to additional complexity. The L<Object::InsideOut> module on CPAN | |
af36000c DR |
830 | provides a comprehensive implementation of this technique, and you may |
831 | see it or other inside-out modules in the wild. | |
832 | ||
e011bc34 DR |
833 | Here is a simple example of the technique, using the |
834 | L<Hash::Util::FieldHash> core module. This module was added to the core | |
835 | to support inside-out object implementations. | |
836 | ||
837 | package Time::InsideOut; | |
838 | ||
839 | use strict; | |
840 | use warnings; | |
841 | ||
842 | use Hash::Util::FieldHash 'fieldhash'; | |
843 | ||
844 | fieldhash my %TIME; | |
845 | ||
846 | sub new { | |
847 | my $class = shift; | |
848 | my $self = bless \( my $empty ), $class; | |
849 | $TIME{$self} = time; | |
850 | ||
851 | $self; | |
852 | } | |
853 | ||
854 | sub epoch { | |
855 | my $self = shift; | |
856 | ||
857 | $TIME{$self}; | |
858 | } | |
859 | ||
860 | my $time = Time::InsideOut->new; | |
861 | print $time->epoch; | |
862 | ||
af36000c DR |
863 | =head2 Pseudo-hashes |
864 | ||
865 | The pseudo-hash feature was an experimental feature introduced in | |
866 | earlier versions of Perl and removed in 5.10.0. A pseudo-hash is an | |
867 | array reference which can be accessed using named keys like a hash. You | |
868 | may run in to some code in the wild which uses it. See the L<fields> | |
869 | pragma for more information. | |
5a964f20 | 870 | |
a0d0e21e LW |
871 | =head1 SEE ALSO |
872 | ||
8257a158 | 873 | A kinder, gentler tutorial on object-oriented programming in Perl can |
af36000c DR |
874 | be found in L<perlootut>. You should also check out L<perlmodlib> for |
875 | some style guides on constructing both modules and classes. | |
876 |