1PERLOBJ(1)             Perl Programmers Reference Guide             PERLOBJ(1)
2
3
4

NAME

6       perlobj - Perl object reference
7

DESCRIPTION

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

SEE ALSO

978       A kinder, gentler tutorial on object-oriented programming in Perl can
979       be found in perlootut. You should also check out perlmodlib for some
980       style guides on constructing both modules and classes.
981
982
983
984perl v5.16.3                      2013-03-04                        PERLOBJ(1)
Impressum