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

SEE ALSO

1019       A kinder, gentler tutorial on object-oriented programming in Perl can
1020       be found in perlootut. You should also check out perlmodlib for some
1021       style guides on constructing both modules and classes.
1022
1023
1024
1025perl v5.36.3                      2023-11-30                        PERLOBJ(1)
Impressum