4 Consistent formatting of this file is achieved with:
5 perl ./Porting/podtidy pod/perlobj.pod
10 perlobj - Perl object reference
14 This document provides a reference for Perl's object orientation
15 features. If you're looking for an introduction to object-oriented
16 programming in Perl, please see L<perlootut>.
18 In order to understand Perl objects, you first need to understand
19 references in Perl. See L<perlref> for details.
21 This document describes all of Perl's object-oriented (OO) features
22 from the ground up. If you're just looking to write some
23 object-oriented code of your own, you are probably better served by
24 using one of the object systems from CPAN described in L<perlootut>.
26 If you're looking to write your own object system, or you need to
27 maintain code which implements objects from scratch then this document
28 will help you understand exactly how Perl does object orientation.
30 There are a few basic principles which define object oriented Perl:
36 An object is simply a reference that knows to which class it belongs.
40 A class is simply a package. A class provides methods that expect to
45 A method is simply a subroutine that expects an object reference (or a
46 package name, for class methods) as the first argument.
50 Let's look at each of these principles in depth.
52 =head2 An Object is Simply a Reference
53 X<object> X<bless> X<constructor> X<new>
55 Unlike many other languages which support object orientation, Perl does
56 not provide any special syntax for constructing an object. A
57 constructor is just a subroutine that returns a reference which has
58 been "blessed" into a class.
60 Here is a simple constructor:
67 return bless {}, $class;
70 The name C<new> isn't special. We could name our constructor something
76 return bless {}, $class;
79 The modern convention for OO modules is to use C<new> as the
80 constructor, but you are free to use the name that works best for your
83 The C<{}> code creates an empty anonymous hash reference. The C<bless>
84 function takes that reference and associates it with the class in
85 C<$class>. In the simplest case, the C<$class> variable will end up
86 containing the string "Critter".
88 We can also call bless with a variable:
99 Once we've blessed C<$self> we can start calling methods on it. This is
100 useful if you want to put object initialization in its own separate
109 $self->_initialize();
114 Since the object is also a hash reference, you can treat it as one,
115 using it store data associated with the object. Typically, code inside
116 the class can treat the hash as reference, while code outside the class
117 should always treat the object as opaque. This is called
118 B<encapsulation>. Encapsulation means that the user of an object does
119 not have to know how it is implemented. The user simply calls
120 documented methods on the object.
122 =head3 Objects Are Blessed; Variables Are Not
124 When we bless something, we are not blessing the variable which
125 contains that thing. This is best demonstrated with this code:
131 print blessed( $bar );
133 This will print out "Class". When we call C<bless> on a variable, we
134 are actually blessing the underlying reference, not the container.
136 =head2 A Class is Simply a Package
137 X<class> X<package> X<@ISA> X<inheritance>
139 Perl does not provide any special syntax for class definitions. A
140 package is simply a namespace containing variables and subroutines. The
141 only difference is that in a class, the subroutines may expect an
142 object or class as the first argument. This is purely a matter of
143 convention, so a class may contain both methods and subroutines which
144 I<don't> operate on an object or class.
146 Each package contains a special array called C<@ISA>. The C<@ISA> array
147 contains a list of that class's parent classes, if any. This array is
148 examined when Perl does method resolution, which we will cover later.
150 It is possible to manually set C<@ISA>, and you may see this in older
151 Perl code. Much older code also uses the L<base> pragma. For new code,
152 we recommend that you use the L<parent> pragma to declare your parents.
153 This pragma will take care of setting C<@ISA>. It will also load the
154 parent classes and make sure that the package doesn't inherit from
157 However the parent classes are set, the package's C<@ISA> variable will
158 contain a list of those parents.
160 All classes inherit from the L<UNIVERSAL> class implicitly. The
161 L<UNIVERSAL> class is implemented by the Perl core, and provides
162 several default methods, such as C<isa()>, C<can()>, and C<VERSION()>.
163 The C<UNIVERSAL> class will I<never> appear in a package's C<@ISA>
166 Perl I<only> provides method inheritance as a built-in feature.
167 Attribute inheritance is left up the class to implement. See the
168 L</Writing Accessors> section for details.
170 =head2 A Method is Simply a Subroutine
173 Perl does not provide any special syntax for defining a method. A
174 method is simply a regular subroutine, and is declared with C<sub>.
175 What makes a method special is that it expects to receive either an
176 object or a class name as its first argument.
178 Perl I<does> provide special syntax for method invocation, the C<< ->
179 >> operator. We will cover this in more detail later.
181 Most methods you write will expect to operate on objects:
186 open my $fh, '>', $self->path()
188 print {$fh} $self->data()
194 =head2 Method Invocation
195 X<invocation> X<method> X<arrow> X<< -> >>
197 Calling a method on an object is written as C<< $object->method >>. The
198 left hand side of the method invocation (or arrow) operator is the
199 object (or class name), and the right hand side is the method name.
201 my $pod = File->new( 'perlobj.pod', $data );
204 The C<< -> >> syntax is also used when dereferencing a reference. It's
205 looks like the same operator, but these are two different operations.
207 When you call a method, the thing on the left side of the arrow is
208 passed as the first argument to the method. That means when we call C<<
209 Critter->new() >>, the C<new()> method receives the string C<"Critter">
210 as its first argument. When we call C<< $fred->speak() >>, the C<$fred>
211 variable is passed as the first argument to C<speak()>.
213 Just as with any Perl subroutine, all of the arguments passed in C<@_>
214 are aliases to the original argument. This includes the object itself.
215 If you assign directly to C<$_[0]> you will change the contents of the
216 variable which references the object. We recommend that you don't do
217 this unless you know exactly what you're doing.
219 Perl knows what package the method is in by looking at the left side of
220 the arrow. If the left hand side is a package name, it looks for the
221 method in the package. If the left hand side is an object, then Perl
222 can tell what class that object has been blessed into.
224 If the left hand side is neither a package name nor an object, then the
225 method call will cause an error, but see the section on L</Method Call
226 Variations> for more nuances.
231 We already talked about the special C<@ISA> array and the L<parent>
234 When a class inherits from another class, any methods defined in the
235 parent class are available in the child class. If you attempt to call a
236 method on an object that isn't defined in its own class, Perl will also
237 look for that method in any parent classes it may have.
240 use parent 'File'; # sets @File::MP3::ISA = ('File');
242 my $mp3 = File::MP3->new( 'Andvari.mp3', $data );
245 Since we didn't define a C<save()> method in the C<File::MP3> class,
246 Perl will look at the C<File::MP3> class's parent classes to find the
247 C<save()> method. If Perl cannot find a C<save()> method anywhere in
248 the inheritance hierarchy, it will die.
250 In this case, it finds it in the C<File> class. Note that the object
251 passed to C<save()> in this case is still a C<File::MP3> object, even
252 though the method is found in the C<File> class.
254 We can override a parent's method in a child class. When we do so, we
255 can still call the parent class's method with the C<SUPER>
261 say 'Prepare to rock';
262 $self->SUPER::save();
265 The C<SUPER> modifier can I<only> be used for method calls. You can't
266 use it for regular subroutine calls:
268 # XXX - This will not work!
270 # This won't work either!
273 =head3 How SUPER is Resolved
276 The C<SUPER> pseudo-class is resolved from the package where the call
277 is made. It is I<not> resolved based on the object's class. This is
278 important, because it lets an inheritance hierarchy several levels deep
279 all call their parent methods.
284 return bless {}, shift;
290 $self->SUPER::speak();
302 $self->SUPER::speak();
314 $self->SUPER::speak();
322 In this example, we will get the following outupt:
328 This demonstrates how C<SUPER> is resolved. Even though the object is
329 blessed into the C<C> class, the C<speak()> method in the C<B> class
330 can still call C<SUPER::speak()>.
332 There are cases where this package-based resolution can be a problem.
333 If you copy a subroutine from one package to another, C<SUPER>
334 resolution will be done based on the original package.
336 =head3 Multiple Inheritance
337 X<multiple inheritance>
339 Multiple inheritance often indicates a design problem, but Perl always
340 give you enough rope to hang yourself with.
342 To declare multiple parents, you simply need to pass multiple class
343 names to C<use parent>:
347 use parent 'Parent1', 'Parent2';
349 =head3 Method Resolution Order
350 X<method resolution order> X<mro>
352 Method resolution order only matters in the case of multiple
353 inheritance. In the case of single inheritance, Perl simply looks up
354 the inheritance chain to find a method:
362 If we call a method on a C<Child> object and that method is not defined
363 in the C<Child> class, Perl will look for that method. in the C<Parent>
364 class and then the C<Grandparent> class.
366 If Perl cannot find the method in any of these classes, it will die
367 with an error message.
369 When a class has multiple parents, the method lookup order becomes more
372 By default, Perl does a depth-first left-to-right search for a method.
373 That means it starts with the first parent in the C<@ISA> array, and
374 then searches all of its parents and so on. If it fails to find the
375 method, it then goes to the next parent in the original class's C<@ISA>
376 array and searches from there.
378 PaternalGrandparent MaternalGrandparent
384 So given the diagram above, Perl will search C<Child>, C<Father>,
385 C<PaternalGrandparent>, C<Mother>, and finally C<MaternalGrandparent>
387 It is possible to ask for a different method resolution order with the
393 use parent 'Father', 'Mother';
395 This pragma lets you switch to the "C3" resolution order. In simple
396 terms, this is a breadth-first order, so Perl will search C<Child>,
397 C<Father>, C<Mother>, C<PaternalGrandparent>, and finally
398 C<MaternalGrandparent>.
400 The C3 order also lets you call methods in sibling classes with the
401 C<next> pseudo-class. See the L<mro> documentation for more details on
404 =head3 Method Resolution Caching
406 When Perl searches for a method, it caches the lookup so that future
407 calls to the method do not need to search for it again. Changing a
408 class's parent class or adding subroutines to a class will invalidate
409 the cache for that class.
411 The L<mro> pragma provides some functions for manipulating the method
414 =head2 Writing Constructors
417 As we mentioned earlier, Perl provides no special constructor syntax.
418 This means that a class must implement its own constructor. A
419 constructor is simply a class method that returns a new object.
421 The constructor can also accept additional parameters that define the
422 object. Let's write a real constructor for the C<File> class we used
429 my ( $path, $data ) = @_;
439 As you can see, we've stored the path and file data in the object
440 itself. Remember, under the hood, this object is still just a hash
441 reference. Later, we'll write accessors to manipulate this data.
443 For our File::MP3 class, we can check to make sure that the path we're
444 given ends with ".mp3":
450 my ( $path, $data ) = @_;
452 die "You cannot create a File::MP3 without an mp3 extension\n"
453 unless $path =~ /\.mp3\z/;
455 return $class->SUPER::new(@_);
458 This constructor lets its parent class do the actual object
464 An attribute is a piece of data belonging to a particular object.
465 Unlike most object-oriented languages, Perl provides no special syntax
466 or support for declaring and manipulating attributes.
468 Attributes are often stored in the object itself. For example, if the
469 object is an anonymous hash reference, we can store the attribute
470 values in the hash using the attribute name as the key.
472 While it's possible to refer directly to these hash keys outside of the
473 class, it's considered a best practice to wrap all access to the
474 attribute with accessor methods.
476 This has several advantages. Accessor make it easier to change the
477 implementation of an object later while still preserving the original
480 An accessor lets you add additional code around attribute access. For
481 example, you could apply a default to an attribute that wasn't set in
482 the constructor, or you could validate that a new value for the
483 attribute is acceptable.
485 Finally, using accessors makes inheritance much simpler. Subclasses can
486 use the accessors rather than having to know the inner details of the
489 =head3 Writing Accessors
492 As with constructors, Perl provides no special accessor declaration
493 syntax, so classes must write them by hand. There are two common types
494 of accessors, read-only and read-write.
496 A simple read-only accessor simply gets the value of a single
502 return $self->{path};
505 A read-write accessor will allow the caller to set the value as well as
512 $self->{path} = shift;
515 return $self->{path};
518 =head2 An Aside About Smarter and Safer Code
520 Our constructor and accessors are not very smart. They don't check that
521 a C<$path> is defined, nor do they check that a C<$path> is a valid
524 Doing these checks by hand can quickly become tedious. Writing a bunch
525 of accessors by hand is also incredibly tedious. There are a lot of
526 modules on CPAN that can help you write safer and more concise code,
527 including the modules we recommend in L<perlootut>.
529 =head2 Method Call Variations
532 Perl supports several other ways to call methods besides the typical
533 C<< $object->method() >> pattern we've seen so far.
535 =head3 Method Names as Strings
537 Perl lets you use a scalar variable containing a string as a method
540 my $file = File->new( $path, $data );
545 This works exactly like calling C<< $file->save() >>. This can be very
546 useful for writing dynamic code. For example, it allows you to pass a
547 method name to be called as a parameter to another method.
549 =head3 Class Names as Strings
551 Perl also lets you use a scalar containing a string as a class name:
555 my $file = $class->new( $path, $data );
557 Again, this allows for very dynamic code.
559 =head3 Subroutine References as Methods
561 You can also call subroutine reference as a method:
571 This is exactly equivalent to writing C<< $sub->($file) >>. You may see
572 this idiom in the wild combined with a call to C<can>:
574 if ( my $meth = $object->can('foo') ) {
578 =head3 Deferencing Method Call
580 Perl also lets you use a dereferenced scalar reference in a method
581 call. That's a mouthful, so let's look at some code:
584 $file->${ returns_scalar_ref() };
585 $file->${ \( returns_scalar() ) };
587 This works if the dereference produces a string I<or> a subroutine
590 =head3 Method Calls on Filehandles
592 Under the hood, Perl filehandles are instances of the C<IO::Handle> or
593 C<IO::File> class. Once you have an open filehandle, you can call
594 methods on it. Additionally, you can call methods on the C<STDING>,
595 C<STDOUT>, and C<STDERR> filehandles.
597 open my $fh, '>', 'path/to/file';
599 $fh->print('content');
603 =head2 Invoking Class Methods
606 Because Perl allows you to use barewords for package names and
607 subroutine names, it can sometimes guess wrong about what you intend a
608 bareword to be. The construct C<< Class->new() >> can be interpreted as
609 C<< Class()->new() >>. In English, that reads as "call a subroutine
610 named Class(), then call new() as a method on the return value".
612 You can force Perl to interpret this as a class method call in two
613 ways. First, you can append a C<::> to the class name:
617 Perl will always interpret this as a method call. You can also quote
622 Of course, if the class name is in a scalar Perl will do the right
628 =head3 Indirect Object Syntax
631 B<Outside of the file handle case, use of this syntax is discouraged,
632 as it can confuse the Perl interpreter. See below for more details.>
634 Perl suports another method invocation syntax called "indirect object"
635 notation. This syntax is called "indirect" because the method comes
636 before the object it is being invoked on.
638 This syntax can be used with any class or object method:
640 my $file = new File $path, $data;
643 We recommend that you avoid this syntax, for several reasons.
645 First, it can be confusing to read. In the above example, it's not
646 clear if C<save> is a method or simply a subroutine that expects a file
647 object as its first argument.
649 When used with class methods, the problem is even worse. Because Perl
650 allows subroutine names to be written as barewords, Perl has to guess
651 whether the bareword after the method is a class name or subroutine
652 name. In other words, Perl can resolve the syntax as either C<<
653 File->new( $path, $data ) >> B<or> C<< new( File( $path, $data ) ) >>.
655 To parse this code, Perl uses a heuristic based on what package names
656 it has seen, what subroutines exist in the current package, what
657 barewords it has previously seen, and other input. Needless to say,
658 heuristics can produce very surprising results!
660 Older documentation (and some CPAN modules) encouraged this syntax,
661 particularly for constructors, so you may still find it in the wild.
662 However, we encourage you to avoid using it in new code.
664 You can force Perl to interpret the bareword as a class name by
665 appending "::" to it, like we saw earlier:
667 my $file = new File:: $path, $data;
669 =head2 C<bless>, C<blessed>, and C<ref>
671 As we saw earlier, an object is simply a reference that has been
672 blessed into a class with the C<bless> function. The C<bless> function
673 can take either one or two arguments:
675 my $object = bless {}, $class;
676 my $object = bless {};
678 In the first form, the anonymous hash reference is being blessed into
679 the class in C<$class>. In the second form, the reference is blessed
680 into the current package.
682 The second form is discouraged, because it breaks the ability of a
683 subclass to reuse the parent's constructor, but you may still run
684 across it in existing code.
686 If you want to know whether a particular scalar refers to an object,
687 you can use the C<blessed> function exported by L<Scalar::Util>, which
688 is shipped with the Perl core.
690 use Scalar::Util 'blessed';
692 if ( blessed($thing) ) { ... }
694 If the C<$thing> has been blessed, then this function returns the name
695 of the package the object has been blessed into. Note that the example
696 above will return false if C<$thing> has been blessed into a class
697 named "0". If the C<$thing> is not a blessed reference, the C<blessed>
698 function returns false.
700 Similarly, Perl's built-in C<ref> function treats a blessed reference
701 specially. If you call C<ref($thing)> and C<$thing> is an object, it
702 will return the name of the class that the object has been blessed
705 If you simply want to check that a variable contains an object, we
706 recommend that you use C<defined blessed($object)>, since C<ref>
707 returns true values for all references, not just objects.
709 =head2 The UNIVERSAL Class
712 All classes automatically inherit from the L<UNIVERSAL> class, which is
713 built-in to the Perl core. This class provides a number of methods, all
714 of which can be called on either a class or an object. You can also
715 choose to override some of these methods in your class. If you do so,
716 we recommend that you follow the built-in semantics described below.
723 The C<isa> method returns I<true> if the object is a member of the
724 class in C<$class>, or a member of a subclass of C<$class>.
729 The C<DOES> method returns I<true> if its object claims to perform the
730 role C<$role>. By default, this is equivalent to C<isa>. This method is
731 provided for use by object system extensions that implement roles, like
732 C<Moose> and C<Role::Tiny>.
734 You can also override C<DOES> directly in your own classes.
739 The C<can> method checks to see if the class or object it was called on
740 has a method named C<$method>. This checks for the method in the class
741 and all of its parents. If the method exists, then a reference to the
742 subroutine is returned. If it does not then C<undef> is returned.
744 If your class responds to method calls via C<AUTOLOAD>, you may want to
745 overload C<can> to return a subroutine reference for methods which your
746 C<AUTOLOAD> method handles.
751 The C<VERSION> method returns the version number of the class
754 If the C<$need> argument is given then it will check that the current
755 version (as defined by the $VERSION variable in the package) is greater
756 than or equal to C<$need>; it will die if this is not the case. This
757 method is called automatically by the C<VERSION> form of C<use>.
759 use Package 1.2 qw(some imported subs);
761 Package->VERSION(1.2);
763 We recommend that you use this method to access another package's
764 version, rather than looking directly at C<$Package::VERSION>. The
765 package you are looking at could have overridden the C<VERSION> method.
767 We also recommend using this method to check whether a module has a
768 sufficient version. The internal implementation uses the L<version>
769 module to make sure that different types of version numbers are
777 If you call a method that doesn't exist in a class, Perl will throw an
778 error. However, if that class or any of its parent classes defined an
779 C<AUTOLOAD> method, that method will be called instead.
781 This is called as a regular method, and the caller will not know the
782 difference. Whatever value your C<AUTOLOAD> method returns is given to
785 The fully qualified method name that was called is available in the
786 C<$AUTOLOAD> package global for your class. Since this is a global, if
787 you want to refer to do it without a package name prefix under C<strict
788 'vars'>, you need to declare it.
790 # XXX - this is a terrible way to implement accessors, but it makes
791 # for a simple example.
796 ( my $called = $AUTOLOAD ) =~ s/.*:://;
798 die "No such attribute: $called"
799 unless exists $self->{$called};
801 return $self->{$called};
804 sub DESTROY { } # see below
806 Without the C<our $AUTOLOAD> declaration, this code will not compile
807 under the L<strict> pragma.
809 As the comment says, this is not a good way to implement accessors.
810 It's slow and too clever by far. See L<perlootut> for recommendations
811 on OO coding in Perl.
813 If your class does have an C<AUTOLOAD> method, we strongly recommend
814 that you override C<can> in your class as well. Your overridden C<can>
815 method should return a subroutine reference for any method that your
816 C<AUTOLOAD> responds to.
819 X<destructor> X<DESTROY>
821 When the last reference to an object goes away, the object is
822 destroyed. If you only have one reference to an object stored in a
823 lexical scalar, the object is destroyed when that scalar goes out of
824 scope. If you store the object in a package global, that object may not
825 go out of scope until the program exits.
827 If you want to do something when the object is destroyed, you can
828 define a C<DESTROY> method in your class. This method will always be
829 called by Perl at the appropriate time, unless the method is empty.
831 This is called just like any other method, with the object as the first
832 argument. It does not receive any additional arguments. However, the
833 C<$_[0]> variable will be read-only in the destructor, so you cannot
834 assign a value to it.
836 If your C<DESTROY> method throws an error, this error will be ignored.
837 It will not be sent to C<STDERR> and it will not cause the program to
838 die. However, if your destructor is running inside an C<eval {}> block,
839 then the error will change the value of C<$@>.
841 Because C<DESTROY> methods can be called at any time, you should
842 localize any global variables you might update in your C<DESTROY>. In
843 particular, if you use C<eval {}> you should localize C<$@>, and if you
844 use C<system> or backticks, you should localize C<$?>.
846 If you define an C<AUTOLOAD> in your class, then Perl will call your
847 C<AUTOLOAD> to handle the C<DESTROY> method. You can prevent this by
848 defining an empty C<DESTROY>, like we did in the example above. You can
849 also check the value of C<$AUTOLOAD> and return without doing anything
850 when called to handle C<DESTROY>.
852 =head3 Global Destruction
854 The order in which objects are destroyed during the global destruction
855 before the program exits is unpredictable. This means that any objects
856 contained by your object may already have been destroyed. You should
857 check that a contained object is defined before calling a method on it:
862 $self->{handle}->close() if $self->{handle};
865 You can use the C<${^GLOBAL_PHASE}> variable to detect if you are
866 currently in the global destruction phase:
871 return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
873 $self->{handle}->close();
876 Note that this variable was added in Perl 5.14.0. If you want to detect
877 the global destruction phase on older versions of Perl, you can use the
878 C<Devel::GlobalDestruction> module on CPAN.
880 If your C<DESTROY> method issues a warning during global destruction,
881 the Perl interpreter will append the string " during global
882 destruction" the warning.
884 During global destruction, Perl will always garbage collect objects
885 before unblessed references. See L<perlhacktips/PERL_DESTRUCT_LEVEL>
886 for more information about global destruction.
888 =head2 Non-Hashref Objects
890 All the examples so far have shown objects based on a blessed hash
891 reference. However, it's possible to bless any type of reference,
892 including scalar refs, glob refs, and code refs. You may see this sort
893 of thing when looking at code in the wild.
895 Here's an example of a module as a blessed scalar:
906 return bless \$time, $class;
914 my $time = Time->new();
915 print $time->epoch();
917 =head2 Inside-Out objects
919 In the past, the Perl community experimented with a technique called
920 "inside-out objects". An inside-out object stores its data outside of
921 the object's reference, indexed on a unique property of the object,
922 such as its memory address, rather than in the object itself.
924 This technique was popular for a while (and was recommended in Damian
925 Conway's I<Perl Best Practices>), but never achieved wide adoption due
926 to additional complexity. The L<Object::InsideOut> module on CPAN
927 provides a comprehensive implementation of this technique, and you may
928 see it or other inside-out modules in the wild.
930 Here is a simple example of the technique, using the
931 L<Hash::Util::FieldHash> core module. This module was added to the core
932 to support inside-out object implementations.
934 package Time::InsideOut;
939 use Hash::Util::FieldHash 'fieldhash';
945 my $self = bless \( my $empty ), $class;
957 my $time = Time::InsideOut->new;
962 The pseudo-hash feature was an experimental feature introduced in
963 earlier versions of Perl and removed in 5.10.0. A pseudo-hash is an
964 array reference which can be accessed using named keys like a hash. You
965 may run in to some code in the wild which uses it. See the L<fields>
966 pragma for more information.
970 A kinder, gentler tutorial on object-oriented programming in Perl can
971 be found in L<perlootut>. You should also check out L<perlmodlib> for
972 some style guides on constructing both modules and classes.