perlobj - Perl object reference
This document provides a reference for Perl's object orientation features. If you're looking for an introduction to object-oriented programming in Perl, please see perlootut.
In order to understand Perl objects, you first need to understand references in Perl. See perlref for details.
This document describes all of Perl's object-oriented (OO) features from the ground up. If you're just looking to write some object-oriented code of your own, you are probably better served by using one of the object systems from CPAN described in perlootut.
If you're looking to write your own object system, or you need to maintain code which implements objects from scratch then this document will help you understand exactly how Perl does object orientation.
There are a few basic principles which define object oriented Perl:
An object is simply a data structure that knows to which class it belongs.
A class is simply a package. A class provides methods that expect to operate on objects.
A method is simply a subroutine that expects a reference to an object (or a package name, for class methods) as the first argument.
Let's look at each of these principles in depth.
Unlike many other languages which support object orientation, Perl does not provide any special syntax for constructing an object. Objects are merely Perl data structures (hashes, arrays, scalars, filehandles, etc.) that have been explicitly associated with a particular class.
That explicit association is created by the built-in bless
function, which is typically used within the constructor subroutine of the class.
Here is a simple constructor:
package File;
sub new {
my $class = shift;
return bless {}, $class;
}
The name new
isn't special. We could name our constructor something else:
package File;
sub load {
my $class = shift;
return bless {}, $class;
}
The modern convention for OO modules is to always use new
as the name for the constructor, but there is no requirement to do so. Any subroutine that blesses a data structure into a class is a valid constructor in Perl.
In the previous examples, the {}
code creates a reference to an empty anonymous hash. The bless
function then takes that reference and associates the hash with the class in $class
. In the simplest case, the $class
variable will end up containing the string "File".
We can also use a variable to store a reference to the data structure that is being blessed as our object:
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}
Once we've blessed the hash referred to by $self
we can start calling methods on it. This is useful if you want to put object initialization in its own separate method:
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$self->_initialize();
return $self;
}
Since the object is also a hash, you can treat it as one, using it to store data associated with the object. Typically, code inside the class can treat the hash as an accessible data structure, while code outside the class should always treat the object as opaque. This is called encapsulation. Encapsulation means that the user of an object does not have to know how it is implemented. The user simply calls documented methods on the object.
Note, however, that (unlike most other OO languages) Perl does not ensure or enforce encapsulation in any way. If you want objects to actually be opaque you need to arrange for that yourself. This can be done in a variety of ways, including using "Inside-Out objects" or modules from CPAN.
When we bless something, we are not blessing the variable which contains a reference to that thing, nor are we blessing the reference that the variable stores; we are blessing the thing that the variable refers to (sometimes known as the referent). This is best demonstrated with this code:
use Scalar::Util 'blessed';
my $foo = {};
my $bar = $foo;
bless $foo, 'Class';
print blessed( $bar ) // 'not blessed'; # prints "Class"
$bar = "some other value";
print blessed( $bar ) // 'not blessed'; # prints "not blessed"
When we call bless
on a variable, we are actually blessing the underlying data structure that the variable refers to. We are not blessing the reference itself, nor the variable that contains that reference. That's why the second call to blessed( $bar )
returns false. At that point $bar
is no longer storing a reference to an object.
You will sometimes see older books or documentation mention "blessing a reference" or describe an object as a "blessed reference", but this is incorrect. It isn't the reference that is blessed as an object; it's the thing the reference refers to (i.e. the referent).
Perl does not provide any special syntax for class definitions. A package is simply a namespace containing variables and subroutines. The only difference is that in a class, the subroutines may expect a reference to an object or the name of a class as the first argument. This is purely a matter of convention, so a class may contain both methods and subroutines which don't operate on an object or class.
Each package contains a special array called @ISA
. The @ISA
array contains a list of that class's parent classes, if any. This array is examined when Perl does method resolution, which we will cover later.
It is possible to manually set @ISA
, and you may see this in older Perl code. Much older code also uses the base pragma. For new code, we recommend that you use the parent pragma to declare your parents. This pragma will take care of setting @ISA
. It will also load the parent classes and make sure that the package doesn't inherit from itself.
However the parent classes are set, the package's @ISA
variable will contain a list of those parents. This is simply a list of scalars, each of which is a string that corresponds to a package name.
All classes inherit from the UNIVERSAL class implicitly. The UNIVERSAL class is implemented by the Perl core, and provides several default methods, such as isa()
, can()
, and VERSION()
. The UNIVERSAL
class will never appear in a package's @ISA
variable.
Perl only provides method inheritance as a built-in feature. Attribute inheritance is left up the class to implement. See the "Writing Accessors" section for details.
Perl does not provide any special syntax for defining a method. A method is simply a regular subroutine, and is declared with sub
. What makes a method special is that it expects to receive either an object or a class name as its first argument.
Perl does provide special syntax for method invocation, the ->
operator. We will cover this in more detail later.
Most methods you write will expect to operate on objects:
sub save {
my $self = shift;
open my $fh, '>', $self->path() or die $!;
print {$fh} $self->data() or die $!;
close $fh or die $!;
}