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

SEE ALSO

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