This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Tweaks to perlootut by Damian
[perl5.git] / pod / perlobj.pod
CommitLineData
af36000c
DR
1=encoding utf8
2
3=for comment
4Consistent formatting of this file is achieved with:
5 perl ./Porting/podtidy pod/perlobj.pod
6
a0d0e21e 7=head1 NAME
d74e8afc 8X<object> X<OOP>
a0d0e21e 9
af36000c 10perlobj - Perl object reference
a0d0e21e
LW
11
12=head1 DESCRIPTION
13
af36000c
DR
14This document provides a reference for Perl's object orientation
15features. If you're looking for an introduction to object-oriented
16programming in Perl, please see L<perlootut>.
17
18In order to understand Perl objects, you first need to understand
19references in Perl. See L<perlref> for details.
a0d0e21e 20
8d26c1a8
DR
21This document describes all of Perl's object-oriented (OO) features
22from the ground up. If you're just looking to write some
23object-oriented code of your own, you are probably better served by
24using one of the object systems from CPAN described in L<perlootut>.
af36000c
DR
25
26If you're looking to write your own object system, or you need to
27maintain code which implements objects from scratch then this document
28will help you understand exactly how Perl does object orientation.
29
30There are a few basic principles which define object oriented Perl:
a0d0e21e
LW
31
32=over 4
33
34=item 1.
35
8d26c1a8 36An object is simply a reference that knows to which class it belongs.
a0d0e21e
LW
37
38=item 2.
39
af36000c
DR
40A class is simply a package. A class provides methods that expect to
41operate on objects.
a0d0e21e
LW
42
43=item 3.
44
af36000c
DR
45A method is simply a subroutine that expects an object reference (or a
46package name, for class methods) as the first argument.
a0d0e21e
LW
47
48=back
49
af36000c 50Let's look at each of these principles in depth.
a0d0e21e
LW
51
52=head2 An Object is Simply a Reference
d74e8afc 53X<object> X<bless> X<constructor> X<new>
a0d0e21e 54
af36000c
DR
55Unlike many other languages which support object orientation, Perl does
56not provide any special syntax for constructing an object. A
57constructor is just a subroutine that returns a reference which has
58been "blessed" into a class.
a0d0e21e 59
af36000c 60Here 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
70The name C<new> isn't special. We could name our constructor something
71else:
5a964f20 72
af36000c
DR
73 sub load {
74 my $class = shift;
75
76 return bless {}, $class;
77 }
78
79The modern convention for OO modules is to use C<new> as the
8d26c1a8
DR
80constructor, but you are free to use the name that works best for your
81class.
af36000c
DR
82
83The C<{}> code creates an empty anonymous hash reference. The C<bless>
84function takes that reference and associates it with the class in
85C<$class>. In the simplest case, the C<$class> variable will end up
86containing the string "Critter".
87
8d26c1a8 88We 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
99Once we've blessed C<$self> we can start calling methods on it. This is
8d26c1a8 100useful if you want to put object initialization in its own separate
af36000c
DR
101method:
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
114Since the object is also a hash reference, you can treat it as one,
115using it store data associated with the object. Typically, code inside
116the class can treat the hash as reference, while code outside the class
117should always treat the object as opaque. This is called
118B<encapsulation>. Encapsulation means that the user of an object does
119not have to know how it is implemented. The user simply calls
120documented methods on the object.
ed850460 121
8d26c1a8
DR
122=head3 Objects Are Blessed; Variables Are Not
123
124When we bless something, we are not blessing the variable which
125contains 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
133This will print out "Class". When we call C<bless> on a variable, we
134are actually blessing the underlying reference, not the container.
135
af36000c
DR
136=head2 A Class is Simply a Package
137X<class> X<package> X<@ISA> X<inheritance>
ed850460 138
af36000c
DR
139Perl does not provide any special syntax for class definitions. A
140package is simply a namespace containing variables and subroutines. The
8d26c1a8
DR
141only difference is that in a class, the subroutines may expect an
142object or class as the first argument. This is purely a matter of
143convention, so a class may contain both methods and subroutines which
144I<don't> operate on an object or class.
af36000c 145
8d26c1a8
DR
146Each package contains a special array called C<@ISA>. The C<@ISA> array
147contains a list of that class's parent classes, if any. This array is
148examined when Perl does method resolution, which we will cover later.
af36000c
DR
149
150It is possible to manually set C<@ISA>, and you may see this in older
8d26c1a8
DR
151Perl code. Much older code also uses the L<base> pragma. For new code,
152we recommend that you use the L<parent> pragma to declare your parents.
153This pragma will take care of setting C<@ISA>. It will also load the
154parent classes and make sure that the package doesn't inherit from
155itself.
156
157However the parent classes are set, the package's C<@ISA> variable will
158contain a list of those parents.
af36000c
DR
159
160All classes inherit from the L<UNIVERSAL> class implicitly. The
161L<UNIVERSAL> class is implemented by the Perl core, and provides
162several default methods, such as C<isa()>, C<can()>, and C<VERSION()>.
8d26c1a8
DR
163The C<UNIVERSAL> class will I<never> appear in a package's C<@ISA>
164variable.
5a964f20 165
af36000c
DR
166Perl I<only> provides method inheritance as a built-in feature.
167Attribute inheritance is left up the class to implement. See the
8d26c1a8 168L</Writing Accessors> section for details.
a0d0e21e
LW
169
170=head2 A Method is Simply a Subroutine
d74e8afc 171X<method>
a0d0e21e 172
af36000c
DR
173Perl does not provide any special syntax for defining a method. A
174method is simply a regular subroutine, and is declared with C<sub>.
175What makes a method special is that it expects to receive either an
176object or a class name as its first argument.
177
178Perl I<does> provide special syntax for method invocation, the C<< ->
179>> operator. We will cover this in more detail later.
180
181Most 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 195X<invocation> X<method> X<arrow> X<< -> >>
a0d0e21e 196
af36000c
DR
197Calling a method on an object is written as C<< $object->method >>. The
198left hand side of the method invocation (or arrow) operator is the
199object (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
204The C<< -> >> syntax is also used when dereferencing a reference. It's
205looks like the same operator, but these are two different operations.
a0d0e21e 206
af36000c
DR
207When you call a method, the thing on the left side of the arrow is
208passed as the first argument to the method. That means when we call C<<
209Critter->new() >>, the C<new()> method receives the string C<"Critter">
210as its first argument. When we call C<< $fred->speak() >>, the C<$fred>
8d26c1a8
DR
211variable is passed as the first argument to C<speak()>.
212
213Just as with any Perl subroutine, all of the arguments passed in C<@_>
214are aliases to the original argument. This includes the object itself.
215If you assign directly to C<$_[0]> you will change the contents of the
216variable which references the object. We recommend that you don't do
217this unless you know exactly what you're doing.
a0d0e21e 218
af36000c
DR
219Perl knows what package the method is in by looking at the left side of
220the arrow. If the left hand side is a package name, it looks for the
221method in the package. If the left hand side is an object, then Perl
222can tell what class that object has been blessed into.
a0d0e21e 223
af36000c
DR
224If the left hand side is neither a package name nor an object, then the
225method call will cause an error, but see the section on L</Method Call
226Variations> for more nuances.
a0d0e21e 227
af36000c
DR
228=head2 Inheritance
229X<inheritance>
a0d0e21e 230
af36000c
DR
231We already talked about the special C<@ISA> array and the L<parent>
232pragma.
a0d0e21e 233
af36000c
DR
234When a class inherits from another class, any methods defined in the
235parent class are available in the child class. If you attempt to call a
236method on an object that isn't defined in its own class, Perl will also
237look 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
245Since we didn't define a C<save()> method in the C<File::MP3> class,
246Perl will look at the C<File::MP3> class's parent classes to find the
8d26c1a8
DR
247C<save()> method. If Perl cannot find a C<save()> method anywhere in
248the inheritance hierarchy, it will die.
af36000c
DR
249
250In this case, it finds it in the C<File> class. Note that the object
251passed to C<save()> in this case is still a C<File::MP3> object, even
252though the method is found in the C<File> class.
a0d0e21e 253
af36000c
DR
254We can override a parent's method in a child class. When we do so, we
255can still call the parent class's method with the C<SUPER>
256pseudo-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
265The C<SUPER> modifier can I<only> be used for method calls. You can't
266use 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 274X<SUPER>
029f3b44 275
af36000c
DR
276The C<SUPER> pseudo-class is resolved from the package where the call
277is made. It is I<not> resolved based on the object's class. This is
278important, because it lets an inheritance hierarchy several levels deep
279all 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 322In this example, we will get the following outupt:
cb1a09d0 323
af36000c
DR
324 A
325 B
326 C
748a9306 327
af36000c
DR
328This demonstrates how C<SUPER> is resolved. Even though the object is
329blessed into the C<C> class, the C<speak()> method in the C<B> class
330can still call C<SUPER::speak()>.
19799a22 331
af36000c
DR
332There are cases where this package-based resolution can be a problem.
333If you copy a subroutine from one package to another, C<SUPER>
334resolution will be done based on the original package.
19799a22 335
af36000c
DR
336=head3 Multiple Inheritance
337X<multiple inheritance>
19799a22 338
af36000c
DR
339Multiple inheritance often indicates a design problem, but Perl always
340give you enough rope to hang yourself with.
19799a22 341
af36000c
DR
342To declare multiple parents, you simply need to pass multiple class
343names 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
350X<method resolution order> X<mro>
351
352Method resolution order only matters in the case of multiple
353inheritance. In the case of single inheritance, Perl simply looks up
354the inheritance chain to find a method:
355
356 Grandparent
357 |
358 Parent
359 |
360 Child
361
362If we call a method on a C<Child> object and that method is not defined
363in the C<Child> class, Perl will look for that method. in the C<Parent>
364class and then the C<Grandparent> class.
365
366If Perl cannot find the method in any of these classes, it will die
367with an error message.
368
369When a class has multiple parents, the method lookup order becomes more
370complicated.
371
372By default, Perl does a depth-first left-to-right search for a method.
373That means it starts with the first parent in the C<@ISA> array, and
374then searches all of its parents and so on. If it fails to find the
375method, it then goes to the next parent in the original class's C<@ISA>
376array and searches from there.
377
378 PaternalGrandparent MaternalGrandparent
379 \ /
380 Father Mother
381 \ /
382 Child
383
384So given the diagram above, Perl will search C<Child>, C<Father>,
385C<PaternalGrandparent>, C<Mother>, and finally C<MaternalGrandparent>
386
387It is possible to ask for a different method resolution order with the
388L<mro> pragma.
389
390 package Child;
391
392 use mro 'c3';
393 use parent 'Father', 'Mother';
394
395This pragma lets you switch to the "C3" resolution order. In simple
396terms, this is a breadth-first order, so Perl will search C<Child>,
397C<Father>, C<Mother>, C<PaternalGrandparent>, and finally
398C<MaternalGrandparent>.
399
400The C3 order also lets you call methods in sibling classes with the
401C<next> pseudo-class. See the L<mro> documentation for more details on
402this feature.
403
404=head3 Method Resolution Caching
405
406When Perl searches for a method, it caches the lookup so that future
407calls to the method do not need to search for it again. Changing a
408class's parent class or adding subroutines to a class will invalidate
409the cache for that class.
410
411The L<mro> pragma provides some functions for manipulating the method
412cache directly.
413
414=head2 Writing Constructors
415X<constructor>
416
417As we mentioned earlier, Perl provides no special constructor syntax.
418This means that a class must implement its own constructor. A
419constructor is simply a class method that returns a new object.
420
421The constructor can also accept additional parameters that define the
422object. Let's write a real constructor for the C<File> class we used
423earlier:
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
439As you can see, we've stored the path and file data in the object
440itself. Remember, under the hood, this object is still just a hash
441reference. Later, we'll write accessors to manipulate this data.
442
443For our File::MP3 class, we can check to make sure that the path we're
444given 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
458This constructor lets its parent class do the actual object
459construction.
460
8d26c1a8
DR
461=head2 Attributes
462X<attribute>
463
464An attribute is a piece of data belonging to a particular object.
465Unlike most object-oriented languages, Perl provides no special syntax
466or support for declaring and manipulating attributes.
467
468Attributes are often stored in the object itself. For example, if the
469object is an anonymous hash reference, we can store the attribute
470values in the hash using the attribute name as the key.
471
472While it's possible to refer directly to these hash keys outside of the
473class, it's considered a best practice to wrap all access to the
474attribute with accessor methods.
475
476This has several advantages. Accessor make it easier to change the
477implementation of an object later while still preserving the original
478API.
479
480An accessor lets you add additional code around attribute access. For
481example, you could apply a default to an attribute that wasn't set in
482the constructor, or you could validate that a new value for the
483attribute is acceptable.
484
485Finally, using accessors makes inheritance much simpler. Subclasses can
486use the accessors rather than having to know the inner details of the
487object.
488
489=head3 Writing Accessors
af36000c
DR
490X<accessor>
491
492As with constructors, Perl provides no special accessor declaration
493syntax, so classes must write them by hand. There are two common types
494of accessors, read-only and read-write.
495
496A simple read-only accessor simply gets the value of a single
497attribute:
498
499 sub path {
500 my $self = shift;
501
502 return $self->{path};
503 }
504
505A read-write accessor will allow the caller to set the value as well as
506get 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
520Our constructor and accessors are not very smart. They don't check that
521a C<$path> is defined, nor do they check that a C<$path> is a valid
522filesystem path.
523
524Doing these checks by hand can quickly become tedious. Writing a bunch
8d26c1a8 525of accessors by hand is also incredibly tedious. There are a lot of
af36000c
DR
526modules on CPAN that can help you write safer and more concise code,
527including the modules we recommend in L<perlootut>.
528
529=head2 Method Call Variations
530X<method>
19799a22 531
af36000c
DR
532Perl supports several other ways to call methods besides the typical
533C<< $object->method() >> pattern we've seen so far.
19799a22 534
af36000c 535=head3 Method Names as Strings
19799a22 536
af36000c
DR
537Perl lets you use a scalar variable containing a string as a method
538name:
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
545This works exactly like calling C<< $file->save() >>. This can be very
546useful for writing dynamic code. For example, it allows you to pass a
547method name to be called as a parameter to another method.
5d9f8747 548
af36000c 549=head3 Class Names as Strings
748a9306 550
af36000c
DR
551Perl 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
557Again, this allows for very dynamic code.
558
559=head3 Subroutine References as Methods
560
561You 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
571This is exactly equivalent to writing C<< $sub->($file) >>. You may see
572this 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
580Perl also lets you use a dereferenced scalar reference in a method
581call. 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
587This works if the dereference produces a string I<or> a subroutine
588reference.
589
590=head3 Method Calls on Filehandles
591
592Under the hood, Perl filehandles are instances of the C<IO::Handle> or
593C<IO::File> class. Once you have an open filehandle, you can call
594methods on it. Additionally, you can call methods on the C<STDING>,
595C<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
604X<invocation>
605
606Because Perl allows you to use barewords for package names and
607subroutine names, it can sometimes guess wrong about what you intend a
608bareword to be. The construct C<< Class->new() >> can be interpreted as
609C<< Class()->new() >>. In English, that reads as "call a subroutine
610named Class(), then call new() as a method on the return value".
611
612You can force Perl to interpret this as a class method call in two
613ways. First, you can append a C<::> to the class name:
614
615 Class::->new()
616
617Perl will always interpret this as a method call. You can also quote
618the class name:
619
620 'Class'->new()
621
622Of course, if the class name is in a scalar Perl will do the right
623thing as well:
624
625 my $class = 'Class';
626 $class->new();
627
628=head3 Indirect Object Syntax
629X<indirect object>
630
631B<Outside of the file handle case, use of this syntax is discouraged,
632as it can confuse the Perl interpreter. See below for more details.>
633
634Perl suports another method invocation syntax called "indirect object"
8d26c1a8
DR
635notation. This syntax is called "indirect" because the method comes
636before the object it is being invoked on.
af36000c
DR
637
638This syntax can be used with any class or object method:
639
640 my $file = new File $path, $data;
641 save $file;
642
643We recommend that you avoid this syntax, for several reasons.
644
645First, it can be confusing to read. In the above example, it's not
646clear if C<save> is a method or simply a subroutine that expects a file
647object as its first argument.
648
649When used with class methods, the problem is even worse. Because Perl
650allows subroutine names to be written as barewords, Perl has to guess
651whether the bareword after the method is a class name or subroutine
652name. In other words, Perl can resolve the syntax as either C<<
653File->new( $path, $data ) >> B<or> C<< new( File( $path, $data ) ) >>.
654
655To parse this code, Perl uses a heuristic based on what package names
8d26c1a8
DR
656it has seen, what subroutines exist in the current package, what
657barewords it has previously seen, and other input. Needless to say,
658heuristics can produce very surprising results!
af36000c
DR
659
660Older documentation (and some CPAN modules) encouraged this syntax,
661particularly for constructors, so you may still find it in the wild.
662However, we encourage you to avoid using it in new code.
663
8d26c1a8
DR
664You can force Perl to interpret the bareword as a class name by
665appending "::" 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
671As we saw earlier, an object is simply a reference that has been
672blessed into a class with the C<bless> function. The C<bless> function
8d26c1a8 673can take either one or two arguments:
af36000c
DR
674
675 my $object = bless {}, $class;
676 my $object = bless {};
677
678In the first form, the anonymous hash reference is being blessed into
679the class in C<$class>. In the second form, the reference is blessed
680into the current package.
681
682The second form is discouraged, because it breaks the ability of a
683subclass to reuse the parent's constructor, but you may still run
684across it in existing code.
685
8d26c1a8
DR
686If you want to know whether a particular scalar refers to an object,
687you can use the C<blessed> function exported by L<Scalar::Util>, which
688is shipped with the Perl core.
af36000c
DR
689
690 use Scalar::Util 'blessed';
691
692 if ( blessed($thing) ) { ... }
693
694If the C<$thing> has been blessed, then this function returns the name
695of the package the object has been blessed into. Note that the example
696above will return false if C<$thing> has been blessed into a class
697named "0". If the C<$thing> is not a blessed reference, the C<blessed>
698function returns false.
699
8d26c1a8 700Similarly, Perl's built-in C<ref> function treats a blessed reference
af36000c
DR
701specially. If you call C<ref($thing)> and C<$thing> is an object, it
702will return the name of the class that the object has been blessed
703into.
704
705If you simply want to check that a variable contains an object, we
8d26c1a8
DR
706recommend that you use C<defined blessed($object)>, since C<ref>
707returns true values for all references, not just objects.
af36000c
DR
708
709=head2 The UNIVERSAL Class
d74e8afc 710X<UNIVERSAL>
a2bdc9a5 711
af36000c 712All classes automatically inherit from the L<UNIVERSAL> class, which is
8d26c1a8 713built-in to the Perl core. This class provides a number of methods, all
af36000c
DR
714of which can be called on either a class or an object. You can also
715choose to override some of these methods in your class. If you do so,
8d26c1a8 716we recommend that you follow the built-in semantics described below.
a2bdc9a5 717
718=over 4
719
af36000c 720=item isa($class)
d74e8afc 721X<isa>
a2bdc9a5 722
af36000c
DR
723The C<isa> method returns I<true> if the object is a member of the
724class in C<$class>, or a member of a subclass of C<$class>.
a2bdc9a5 725
af36000c 726=item DOES($role)
003db2bd 727X<DOES>
bcb8f0e8 728
af36000c
DR
729The C<DOES> method returns I<true> if its object claims to perform the
730role C<$role>. By default, this is equivalent to C<isa>. This method is
731provided for use by object system extensions that implement roles, like
732C<Moose> and C<Role::Tiny>.
bcb8f0e8 733
8d26c1a8
DR
734You can also override C<DOES> directly in your own classes.
735
af36000c 736=item can($method)
d74e8afc 737X<can>
a2bdc9a5 738
8d26c1a8
DR
739The C<can> method checks to see if the class or object it was called on
740has a method named C<$method>. This checks for the method in the class
741and all of its parents. If the method exists, then a reference to the
742subroutine is returned. If it does not then C<undef> is returned.
b32b0a5d 743
af36000c 744If your class responds to method calls via C<AUTOLOAD>, you may want to
8d26c1a8
DR
745overload C<can> to return a subroutine reference for methods which your
746C<AUTOLOAD> method handles.
af36000c
DR
747
748=item VERSION($need)
d74e8afc 749X<VERSION>
760ac839 750
af36000c
DR
751The C<VERSION> method returns the version number of the class
752(package).
753
754If the C<$need> argument is given then it will check that the current
755version (as defined by the $VERSION variable in the package) is greater
756than or equal to C<$need>; it will die if this is not the case. This
757method 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
763We recommend that you use this method to access another package's
764version, rather than looking directly at C<$Package::VERSION>. The
765package you are looking at could have overridden the C<VERSION> method.
766
767We also recommend using this method to check whether a module has a
768sufficient version. The internal implementation uses the L<version>
769module to make sure that different types of version numbers are
770compared correctly.
771
a2bdc9a5 772=back
773
af36000c
DR
774=head2 AUTOLOAD
775X<AUTOLOAD>
776
777If you call a method that doesn't exist in a class, Perl will throw an
778error. However, if that class or any of its parent classes defined an
779C<AUTOLOAD> method, that method will be called instead.
780
781This is called as a regular method, and the caller will not know the
782difference. Whatever value your C<AUTOLOAD> method returns is given to
783the caller.
784
785The fully qualified method name that was called is available in the
786C<$AUTOLOAD> package global for your class. Since this is a global, if
995ab4ef
DR
787you 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
806Without the C<our $AUTOLOAD> declaration, this code will not compile
807under the L<strict> pragma.
808
809As the comment says, this is not a good way to implement accessors.
810It's slow and too clever by far. See L<perlootut> for recommendations
811on OO coding in Perl.
812
813If your class does have an C<AUTOLOAD> method, we strongly recommend
814that you override C<can> in your class as well. Your overridden C<can>
815method should return a subroutine reference for any method that your
816C<AUTOLOAD> responds to.
817
54310121 818=head2 Destructors
d74e8afc 819X<destructor> X<DESTROY>
a0d0e21e 820
8d26c1a8
DR
821When the last reference to an object goes away, the object is
822destroyed. If you only have one reference to an object stored in a
823lexical scalar, the object is destroyed when that scalar goes out of
824scope. If you store the object in a package global, that object may not
825go out of scope until the program exits.
af36000c
DR
826
827If you want to do something when the object is destroyed, you can
8d26c1a8
DR
828define a C<DESTROY> method in your class. This method will always be
829called by Perl at the appropriate time, unless the method is empty.
af36000c
DR
830
831This is called just like any other method, with the object as the first
8d26c1a8
DR
832argument. It does not receive any additional arguments. However, the
833C<$_[0]> variable will be read-only in the destructor, so you cannot
834assign a value to it.
835
836If your C<DESTROY> method throws an error, this error will be ignored.
837It will not be sent to C<STDERR> and it will not cause the program to
838die. However, if your destructor is running inside an C<eval {}> block,
839then the error will change the value of C<$@>.
af36000c
DR
840
841Because C<DESTROY> methods can be called at any time, you should
842localize any global variables you might update in your C<DESTROY>. In
843particular, if you use C<eval {}> you should localize C<$@>, and if you
844use C<system> or backticks, you should localize C<$?>.
845
8d26c1a8
DR
846If you define an C<AUTOLOAD> in your class, then Perl will call your
847C<AUTOLOAD> to handle the C<DESTROY> method. You can prevent this by
848defining an empty C<DESTROY>, like we did in the example above. You can
849also check the value of C<$AUTOLOAD> and return without doing anything
850when called to handle C<DESTROY>.
851
852=head3 Global Destruction
af36000c 853
8d26c1a8
DR
854The order in which objects are destroyed during the global destruction
855before the program exits is unpredictable. This means that any objects
856contained by your object may already have been destroyed. You should
857check 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
865You can use the C<${^GLOBAL_PHASE}> variable to detect if you are
8d26c1a8 866currently 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
876Note that this variable was added in Perl 5.14.0. If you want to detect
8d26c1a8 877the global destruction phase on older versions of Perl, you can use the
af36000c
DR
878C<Devel::GlobalDestruction> module on CPAN.
879
8d26c1a8
DR
880If your C<DESTROY> method issues a warning during global destruction,
881the Perl interpreter will append the string " during global
882destruction" the warning.
883
884During global destruction, Perl will always garbage collect objects
995ab4ef
DR
885before unblessed references. See L<perlhacktips/PERL_DESTRUCT_LEVEL>
886for more information about global destruction.
8d26c1a8 887
af36000c
DR
888=head2 Non-Hashref Objects
889
890All the examples so far have shown objects based on a blessed hash
891reference. However, it's possible to bless any type of reference,
892including scalar refs, glob refs, and code refs. You may see this sort
893of thing when looking at code in the wild.
894
895Here'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 919In 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
921the object's reference, indexed on a unique property of the object,
922such as its memory address, rather than in the object itself.
af36000c 923
e011bc34
DR
924This technique was popular for a while (and was recommended in Damian
925Conway's I<Perl Best Practices>), but never achieved wide adoption due
926to additional complexity. The L<Object::InsideOut> module on CPAN
af36000c
DR
927provides a comprehensive implementation of this technique, and you may
928see it or other inside-out modules in the wild.
929
e011bc34
DR
930Here is a simple example of the technique, using the
931L<Hash::Util::FieldHash> core module. This module was added to the core
932to 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
962The pseudo-hash feature was an experimental feature introduced in
963earlier versions of Perl and removed in 5.10.0. A pseudo-hash is an
964array reference which can be accessed using named keys like a hash. You
965may run in to some code in the wild which uses it. See the L<fields>
966pragma for more information.
5a964f20 967
a0d0e21e
LW
968=head1 SEE ALSO
969
8257a158 970A kinder, gentler tutorial on object-oriented programming in Perl can
af36000c
DR
971be found in L<perlootut>. You should also check out L<perlmodlib> for
972some style guides on constructing both modules and classes.
973