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