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