This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add more details on inside-out objects from David Golden, and an inside-out class...
[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
af36000c
DR
21This document describes all of Perl's OO features from the ground up.
22If you're just looking to write some object-oriented code of your own,
23you are probably better served by using one of the object systems from
24CPAN described in L<perlootut>.
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
af36000c 36An object is simply a reference that knows which class it belongs to.
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
80constructor, but you are free to use the name if that works best for
81your class.
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
88We 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
99Once we've blessed C<$self> we can start calling methods on it. This is
100useful if you want to break out object initialization to its own
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
af36000c
DR
122=head2 A Class is Simply a Package
123X<class> X<package> X<@ISA> X<inheritance>
ed850460 124
af36000c
DR
125Perl does not provide any special syntax for class definitions. A
126package is simply a namespace containing variables and subroutines. The
127only difference is that in a class, the subroutines expect an object or
128class as the first argument.
129
130Each package contains a special array reference called C<@ISA>. The
131C<@ISA> array contains a list of that class's parent classes, if any.
132This array is examined when Perl does method resolution, which we will
133cover later.
134
135It is possible to manually set C<@ISA>, and you may see this in older
136Perl code. For new code, we recommend that you use the L<parent> pragma
137to declare your parents. This pragma will take care of setting C<@ISA>.
138It will also load the parent classes and make sure that the package
139doesn't inherit from itself.
140
141All classes inherit from the L<UNIVERSAL> class implicitly. The
142L<UNIVERSAL> class is implemented by the Perl core, and provides
143several default methods, such as C<isa()>, C<can()>, and C<VERSION()>.
144X<UNIVERSAL> X<base class> X<class, base>
5a964f20 145
af36000c
DR
146Perl I<only> provides method inheritance as a built-in feature.
147Attribute inheritance is left up the class to implement. See the
148L</Attributes> section for details.
a0d0e21e
LW
149
150=head2 A Method is Simply a Subroutine
d74e8afc 151X<method>
a0d0e21e 152
af36000c
DR
153Perl does not provide any special syntax for defining a method. A
154method is simply a regular subroutine, and is declared with C<sub>.
155What makes a method special is that it expects to receive either an
156object or a class name as its first argument.
157
158Perl I<does> provide special syntax for method invocation, the C<< ->
159>> operator. We will cover this in more detail later.
160
161Most 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 175X<invocation> X<method> X<arrow> X<< -> >>
a0d0e21e 176
af36000c
DR
177Calling a method on an object is written as C<< $object->method >>. The
178left hand side of the method invocation (or arrow) operator is the
179object (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
184The C<< -> >> operator is also used when dereferencing a reference.
185It's the same operator, but it has two different uses.
a0d0e21e 186
af36000c
DR
187When you call a method, the thing on the left side of the arrow is
188passed as the first argument to the method. That means when we call C<<
189Critter->new() >>, the C<new()> method receives the string C<"Critter">
190as its first argument. When we call C<< $fred->speak() >>, the C<$fred>
191object is passed as the first argument to C<speak()>
a0d0e21e 192
af36000c
DR
193Perl knows what package the method is in by looking at the left side of
194the arrow. If the left hand side is a package name, it looks for the
195method in the package. If the left hand side is an object, then Perl
196can tell what class that object has been blessed into.
a0d0e21e 197
af36000c
DR
198If the left hand side is neither a package name nor an object, then the
199method call will cause an error, but see the section on L</Method Call
200Variations> for more nuances.
a0d0e21e 201
af36000c
DR
202=head2 Inheritance
203X<inheritance>
a0d0e21e 204
af36000c
DR
205We already talked about the special C<@ISA> array and the L<parent>
206pragma.
a0d0e21e 207
af36000c
DR
208When a class inherits from another class, any methods defined in the
209parent class are available in the child class. If you attempt to call a
210method on an object that isn't defined in its own class, Perl will also
211look 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
219Since we didn't define a C<save()> method in the C<File::MP3> class,
220Perl will look at the C<File::MP3> class's parent classes to find the
221C<save()> method. If Perl could not find a C<save()> method anywhere in
222the inheritance hierarchy, it would die.
223
224In this case, it finds it in the C<File> class. Note that the object
225passed to C<save()> in this case is still a C<File::MP3> object, even
226though the method is found in the C<File> class.
a0d0e21e 227
af36000c
DR
228We can override a parent's method in a child class. When we do so, we
229can still call the parent class's method with the C<SUPER>
230pseudo-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
239The C<SUPER> modifier can I<only> be used for method calls. You can't
240use 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 248X<SUPER>
029f3b44 249
af36000c
DR
250The C<SUPER> pseudo-class is resolved from the package where the call
251is made. It is I<not> resolved based on the object's class. This is
252important, because it lets an inheritance hierarchy several levels deep
253all 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 296In this example, we will get the following outupt:
cb1a09d0 297
af36000c
DR
298 A
299 B
300 C
748a9306 301
af36000c
DR
302This demonstrates how C<SUPER> is resolved. Even though the object is
303blessed into the C<C> class, the C<speak()> method in the C<B> class
304can still call C<SUPER::speak()>.
19799a22 305
af36000c
DR
306There are cases where this package-based resolution can be a problem.
307If you copy a subroutine from one package to another, C<SUPER>
308resolution will be done based on the original package.
19799a22 309
af36000c
DR
310=head3 Multiple Inheritance
311X<multiple inheritance>
19799a22 312
af36000c
DR
313Multiple inheritance often indicates a design problem, but Perl always
314give you enough rope to hang yourself with.
19799a22 315
af36000c
DR
316To declare multiple parents, you simply need to pass multiple class
317names 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
324X<method resolution order> X<mro>
325
326Method resolution order only matters in the case of multiple
327inheritance. In the case of single inheritance, Perl simply looks up
328the inheritance chain to find a method:
329
330 Grandparent
331 |
332 Parent
333 |
334 Child
335
336If we call a method on a C<Child> object and that method is not defined
337in the C<Child> class, Perl will look for that method. in the C<Parent>
338class and then the C<Grandparent> class.
339
340If Perl cannot find the method in any of these classes, it will die
341with an error message.
342
343When a class has multiple parents, the method lookup order becomes more
344complicated.
345
346By default, Perl does a depth-first left-to-right search for a method.
347That means it starts with the first parent in the C<@ISA> array, and
348then searches all of its parents and so on. If it fails to find the
349method, it then goes to the next parent in the original class's C<@ISA>
350array and searches from there.
351
352 PaternalGrandparent MaternalGrandparent
353 \ /
354 Father Mother
355 \ /
356 Child
357
358So given the diagram above, Perl will search C<Child>, C<Father>,
359C<PaternalGrandparent>, C<Mother>, and finally C<MaternalGrandparent>
360
361It is possible to ask for a different method resolution order with the
362L<mro> pragma.
363
364 package Child;
365
366 use mro 'c3';
367 use parent 'Father', 'Mother';
368
369This pragma lets you switch to the "C3" resolution order. In simple
370terms, this is a breadth-first order, so Perl will search C<Child>,
371C<Father>, C<Mother>, C<PaternalGrandparent>, and finally
372C<MaternalGrandparent>.
373
374The C3 order also lets you call methods in sibling classes with the
375C<next> pseudo-class. See the L<mro> documentation for more details on
376this feature.
377
378=head3 Method Resolution Caching
379
380When Perl searches for a method, it caches the lookup so that future
381calls to the method do not need to search for it again. Changing a
382class's parent class or adding subroutines to a class will invalidate
383the cache for that class.
384
385The L<mro> pragma provides some functions for manipulating the method
386cache directly.
387
388=head2 Writing Constructors
389X<constructor>
390
391As we mentioned earlier, Perl provides no special constructor syntax.
392This means that a class must implement its own constructor. A
393constructor is simply a class method that returns a new object.
394
395The constructor can also accept additional parameters that define the
396object. Let's write a real constructor for the C<File> class we used
397earlier:
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
413As you can see, we've stored the path and file data in the object
414itself. Remember, under the hood, this object is still just a hash
415reference. Later, we'll write accessors to manipulate this data.
416
417For our File::MP3 class, we can check to make sure that the path we're
418given 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
432This constructor lets its parent class do the actual object
433construction.
434
435=head2 Writing Accessors
436X<accessor>
437
438As with constructors, Perl provides no special accessor declaration
439syntax, so classes must write them by hand. There are two common types
440of accessors, read-only and read-write.
441
442A simple read-only accessor simply gets the value of a single
443attribute:
444
445 sub path {
446 my $self = shift;
447
448 return $self->{path};
449 }
450
451A read-write accessor will allow the caller to set the value as well as
452get 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
466Our constructor and accessors are not very smart. They don't check that
467a C<$path> is defined, nor do they check that a C<$path> is a valid
468filesystem path.
469
470Doing these checks by hand can quickly become tedious. Writing a bunch
471of accessors by hand is also incredibly tedioud. There are a lot of
472modules on CPAN that can help you write safer and more concise code,
473including the modules we recommend in L<perlootut>.
474
475=head2 Method Call Variations
476X<method>
19799a22 477
af36000c
DR
478Perl supports several other ways to call methods besides the typical
479C<< $object->method() >> pattern we've seen so far.
19799a22 480
af36000c 481=head3 Method Names as Strings
19799a22 482
af36000c
DR
483Perl lets you use a scalar variable containing a string as a method
484name:
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
491This works exactly like calling C<< $file->save() >>. This can be very
492useful for writing dynamic code. For example, it allows you to pass a
493method name to be called as a parameter to another method.
5d9f8747 494
af36000c 495=head3 Class Names as Strings
748a9306 496
af36000c
DR
497Perl 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
503Again, this allows for very dynamic code.
504
505=head3 Subroutine References as Methods
506
507You 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
517This is exactly equivalent to writing C<< $sub->($file) >>. You may see
518this 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
525X<invocation>
526
527Because Perl allows you to use barewords for package names and
528subroutine names, it can sometimes guess wrong about what you intend a
529bareword to be. The construct C<< Class->new() >> can be interpreted as
530C<< Class()->new() >>. In English, that reads as "call a subroutine
531named Class(), then call new() as a method on the return value".
532
533You can force Perl to interpret this as a class method call in two
534ways. First, you can append a C<::> to the class name:
535
536 Class::->new()
537
538Perl will always interpret this as a method call. You can also quote
539the class name:
540
541 'Class'->new()
542
543Of course, if the class name is in a scalar Perl will do the right
544thing as well:
545
546 my $class = 'Class';
547 $class->new();
548
549=head3 Indirect Object Syntax
550X<indirect object>
551
552B<Outside of the file handle case, use of this syntax is discouraged,
553as it can confuse the Perl interpreter. See below for more details.>
554
555Perl suports another method invocation syntax called "indirect object"
556notation.
557
558This notation is quite common when used with file handles:
559
560 print $fh $data;
561
562This is really like calling C<< $fh->print($data) >>. This syntax is
563called "indirect" because the method comes before the object it is
564being invoked on.
565
566This syntax can be used with any class or object method:
567
568 my $file = new File $path, $data;
569 save $file;
570
571We recommend that you avoid this syntax, for several reasons.
572
573First, it can be confusing to read. In the above example, it's not
574clear if C<save> is a method or simply a subroutine that expects a file
575object as its first argument.
576
577When used with class methods, the problem is even worse. Because Perl
578allows subroutine names to be written as barewords, Perl has to guess
579whether the bareword after the method is a class name or subroutine
580name. In other words, Perl can resolve the syntax as either C<<
581File->new( $path, $data ) >> B<or> C<< new( File( $path, $data ) ) >>.
582
583To parse this code, Perl uses a heuristic based on what package names
584it has seen, what subroutines exist in the current package, and what
585barewords it has seen previously. Needless to say, heuristics can
586produce very surprising results!
587
588Older documentation (and some CPAN modules) encouraged this syntax,
589particularly for constructors, so you may still find it in the wild.
590However, we encourage you to avoid using it in new code.
591
592=head2 C<bless>, C<blessed>, and C<ref>
593
594As we saw earlier, an object is simply a reference that has been
595blessed into a class with the C<bless> function. The C<bless> function
596has can take either one or two arguments:
597
598 my $object = bless {}, $class;
599 my $object = bless {};
600
601In the first form, the anonymous hash reference is being blessed into
602the class in C<$class>. In the second form, the reference is blessed
603into the current package.
604
605The second form is discouraged, because it breaks the ability of a
606subclass to reuse the parent's constructor, but you may still run
607across it in existing code.
608
609If you want to know whether a particular scalar is an object, you can
610use the C<blessed> function exported by L<Scalar::Util>, which is
611shipped with the Perl core.
612
613 use Scalar::Util 'blessed';
614
615 if ( blessed($thing) ) { ... }
616
617If the C<$thing> has been blessed, then this function returns the name
618of the package the object has been blessed into. Note that the example
619above will return false if C<$thing> has been blessed into a class
620named "0". If the C<$thing> is not a blessed reference, the C<blessed>
621function returns false.
622
623Similarly, Perl's built in C<ref> function treats a blessed reference
624specially. If you call C<ref($thing)> and C<$thing> is an object, it
625will return the name of the class that the object has been blessed
626into.
627
628If you simply want to check that a variable contains an object, we
629recommend that you use C<blessed>, since C<ref> returns true values for
630all references, not just objects.
631
632=head2 The UNIVERSAL Class
d74e8afc 633X<UNIVERSAL>
a2bdc9a5 634
af36000c
DR
635All classes automatically inherit from the L<UNIVERSAL> class, which is
636built in to the Perl core. This class provides a number of methods, all
637of which can be called on either a class or an object. You can also
638choose to override some of these methods in your class. If you do so,
639we recommend that you follow the built in semantics described below.
a2bdc9a5 640
641=over 4
642
af36000c 643=item isa($class)
d74e8afc 644X<isa>
a2bdc9a5 645
af36000c
DR
646The C<isa> method returns I<true> if the object is a member of the
647class in C<$class>, or a member of a subclass of C<$class>.
a2bdc9a5 648
af36000c 649=item DOES($role)
003db2bd 650X<DOES>
bcb8f0e8 651
af36000c
DR
652The C<DOES> method returns I<true> if its object claims to perform the
653role C<$role>. By default, this is equivalent to C<isa>. This method is
654provided for use by object system extensions that implement roles, like
655C<Moose> and C<Role::Tiny>.
bcb8f0e8 656
af36000c 657=item can($method)
d74e8afc 658X<can>
a2bdc9a5 659
af36000c
DR
660The C<can> method checks to see if its object has a method called
661C<$method>. If it does, then a reference to the subroutine is returned.
662If it does not then C<undef> is returned.
663
664This will return true if the object's class or any of it's parent
665classes contain C<$method>.
b32b0a5d 666
af36000c
DR
667If your class responds to method calls via C<AUTOLOAD>, you may want to
668overload C<can> to respond true for methods which C<AUTOLOAD> handles.
669
670=item VERSION($need)
d74e8afc 671X<VERSION>
760ac839 672
af36000c
DR
673The C<VERSION> method returns the version number of the class
674(package).
675
676If the C<$need> argument is given then it will check that the current
677version (as defined by the $VERSION variable in the package) is greater
678than or equal to C<$need>; it will die if this is not the case. This
679method 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
685We recommend that you use this method to access another package's
686version, rather than looking directly at C<$Package::VERSION>. The
687package you are looking at could have overridden the C<VERSION> method.
688
689We also recommend using this method to check whether a module has a
690sufficient version. The internal implementation uses the L<version>
691module to make sure that different types of version numbers are
692compared correctly.
693
a2bdc9a5 694=back
695
af36000c
DR
696=head2 AUTOLOAD
697X<AUTOLOAD>
698
699If you call a method that doesn't exist in a class, Perl will throw an
700error. However, if that class or any of its parent classes defined an
701C<AUTOLOAD> method, that method will be called instead.
702
703This is called as a regular method, and the caller will not know the
704difference. Whatever value your C<AUTOLOAD> method returns is given to
705the caller.
706
707The fully qualified method name that was called is available in the
708C<$AUTOLOAD> package global for your class. Since this is a global, if
709you want to refer to do it without a package name prefix, you need to
710declare 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
728Without the C<our $AUTOLOAD> declaration, this code will not compile
729under the L<strict> pragma.
730
731As the comment says, this is not a good way to implement accessors.
732It's slow and too clever by far. See L<perlootut> for recommendations
733on OO coding in Perl.
734
735If your class does have an C<AUTOLOAD> method, we strongly recommend
736that you override C<can> in your class as well. Your overridden C<can>
737method should return a subroutine reference for any method that your
738C<AUTOLOAD> responds to.
739
54310121 740=head2 Destructors
d74e8afc 741X<destructor> X<DESTROY>
a0d0e21e 742
af36000c
DR
743When the last refernce to an object goes away, the object is destroyed.
744If you only have one reference to an object stored in a lexical scalar,
745the object is destroyed when that lexical goes out of scope. If you
746store the object in a global, that object may not go out of scope until
747the program exits.
748
749If you want to do something when the object is destroyed, you can
750defined a C<DESTROY> method in your class. This method will always be
751called by Perl at the appropriate time.
752
753This is called just like any other method, with the object as the first
754argument. It does not receive any additional arguments.
755
756Because C<DESTROY> methods can be called at any time, you should
757localize any global variables you might update in your C<DESTROY>. In
758particular, if you use C<eval {}> you should localize C<$@>, and if you
759use C<system> or backticks, you should localize C<$?>.
760
761As we saw in the C<AUTOLOAD> example, if you define an C<AUTOLOAD>
762method, this will be called for the C<DESTROY> method, so you need to
763handle this case in your C<AUTOLOAD>.
764
765The order in which objects are destroyed when the program exits is
766unpredictable. This means that any objects contained by your object may
767already have been destroyed. This means you should check that they are
768defined before calling methods on them:
769
770 sub DESTROY {
771 my $self = shift;
772
773 $self->{handle}->close() if $self->{handle};
774 }
775
776You can use the C<${^GLOBAL_PHASE}> variable to detect if you are
777currently 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
787Note that this variable was added in Perl 5.14.0. If you want to detect
788program exit on older versions of Perl, you can use the
789C<Devel::GlobalDestruction> module on CPAN.
790
791=head2 Non-Hashref Objects
792
793All the examples so far have shown objects based on a blessed hash
794reference. However, it's possible to bless any type of reference,
795including scalar refs, glob refs, and code refs. You may see this sort
796of thing when looking at code in the wild.
797
798Here'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
822In the past, the Perl community experimented with a technique called
823"inside-out objects". An inside-out object stores its data in a lexical
824class variable, indexed on a unique property of the object, such as its
825memory address, rather than in the object itself.
af36000c 826
e011bc34
DR
827This technique was popular for a while (and was recommended in Damian
828Conway's I<Perl Best Practices>), but never achieved wide adoption due
829to additional complexity. The L<Object::InsideOut> module on CPAN
af36000c
DR
830provides a comprehensive implementation of this technique, and you may
831see it or other inside-out modules in the wild.
832
e011bc34
DR
833Here is a simple example of the technique, using the
834L<Hash::Util::FieldHash> core module. This module was added to the core
835to 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
865The pseudo-hash feature was an experimental feature introduced in
866earlier versions of Perl and removed in 5.10.0. A pseudo-hash is an
867array reference which can be accessed using named keys like a hash. You
868may run in to some code in the wild which uses it. See the L<fields>
869pragma for more information.
5a964f20 870
a0d0e21e
LW
871=head1 SEE ALSO
872
8257a158 873A kinder, gentler tutorial on object-oriented programming in Perl can
af36000c
DR
874be found in L<perlootut>. You should also check out L<perlmodlib> for
875some style guides on constructing both modules and classes.
876