An introduction to object-oriented Perl
Ian Malpass
Frozen Perl
February 2008
Terminology
Object
- A container for data.
- An object's data items are called its attributes.
- Provides an access mechanism for the data it contains.
- In Perl: a reference (often a hashref) that has been told which class it belongs to, using
bless().
Class
- A specification of an object's attributes and methods.
- Classes can have attributes and methods too - they apply to all objects of that class.
- The class defines the object's interface - how you can talk to the object and how it will respond.
- In Perl: a package.
Method
- A routine for accessing the attributes of an object or class.
- In Perl: a subroutine, defined in its class's package.
Using Perl objects
Load your classes
- If your class definitions are in external modules, use the use function to load the modules:
use Person;
- perl looks for modules in the locations stored in the global array
@INC. Use thelibpragma to specify other places for perl to look:use lib qw( ./lib ); # adds "lib" in the current directory to the search path
Create your object
- The method used to create an object is called a constructor. Constructors in Perl are often called
new. - The method-calling operator is
->. The syntax is:[object ref or class name]->[method name]([arguments])
my $ian = Person->new();
Use your objects
- Accessors are methods used to set and get object data:
$ian->firstName( 'Ian' ); $ian->lastName( 'Malpass' );
- Other methods do useful stuff with the data:
print $ian->fullName() . "\n";
Creating your own class
Name your package
- Decide on a name for your class, and therefore its package.
- It is common to put class definitions in Perl modules.
Personwould go in the filePerson.pm.Person::Addresswould go in the filePerson/Address.pm.
Create your package
- perl expects packages to return true value; it is usual to put a
1at the end of the file to do this.package Person; # Class code goes here 1;
Create a constructor
- A method is a subroutine in your class's package.
- The first argument to any method is the class name (for class methods) or a reference to the object itself (for object methods).
- A constructor is a method that returns a reference which has been blessed.
Example constructor
sub new {
my $class = shift; # class name is the first argument
my $self = bless {}, $class; # use bless to tell the ref its class
return $self; # return the new object
}bless()doesn't need to take a second argument, but it's good practice to give one - it makes some advanced OO techniques like inheritance work properly.- The object here is a blessed hashref, but any reference can be blessed. The referenced data structure is used to store the object's attribute data.
- Most constructors take additional arguments to initialise the object, etc.
Create accessors
- Accessors set and/or retrieve data in the object (a hashref in our example).
- Most accessors have much the same form.
- There are various ways to avoid having to cut-and-paste accessors, which are beyond the scope of this talk.
Example accessor
sub firstName {
my ( $self, $firstName ) = @_;
if ( defined $firstName ) {
$self->{ firstName } = $firstName ;
}
return $self->{ firstName };
}$selfis a common variable for storing the object reference (the first argument for this object method).$selfworks like a normal hashref.
Create other methods
- Create the methods that will make the object actually useful!
- Methods should call other methods in their class, rather than accessing the attribute data directly.
- This is less efficient, but using the object's interface means you can change the object's internals with less effort.
Example method
sub fullName {
my $self = shift;
return $self->firstName() . " " . $self->lastName();
}Inheritance
- A class says it will inherit from one or more other classes.
- If perl can't find a method in the current class, it looks for it in the base classes.
- Base classes are listed in the package's
@ISAvariable.
Example: the Friend class
package Friend; use Person; @ISA = qw( Person ); 1;
Friendinherits all the methods defined inPerson.
use base
- The
basemodule does theuse()and@ISAwork in one step.package Friend; use base qw( Person ); 1;
Inherited constructors
my $friend = Friend->new(); print ref $friend; # prints "Friend"
- Inherits
new()method fromPerson. - Two-argument form of
bless()blesses object asFriend, notPerson.- If we had used the one-argument form, it would have blessed the object into the current package (
Person) not the calling package (Friend).
- If we had used the one-argument form, it would have blessed the object into the current package (
Overriding inherited methods
- Just define a new subroutine in your subclass.
Example: overriding a method
package Friend;
use base qw( Person );
sub fullName {
my $self = shift;
return "My friend " . $self->firstName . " " . $self->lastName;
}
my $friend = Friend->new;
$friend->firstName( "Joe" );
$friend->lastName( "Bloggs" );
print $friend->fullName; # prints "My friend Joe Bloggs"- We use the inherited
firstName()andlastName()methods fromPersonbut create our ownfullName()method.
Referring to the parent class
- Perl defines the
SUPERpseudo-package. SUPERrefers to the parent class of the current class, not the calling class.- Allows you to call all the way up a long inheritance chain.
GoodBuddyinherits fromFriendwhich inherits fromPerson.GoodBuddy->fullNamecan callFriend->fullNameusingSUPER, which can callPerson->fullName, etc.
- Can refer to any method in the parent class using
SUPER.
Example: referring to a parent class's method
package Friend;
use base qw( Person );
sub fullName {
my $self = shift;
return "My friend " . $self->SUPER::fullName();
}
my $friend = Friend->new;
$friend->firstName( "Joe" );
$friend->lastName( "Bloggs" );
print $friend->fullName; # prints "My friend Joe Bloggs"See also
This introduction, expanded
This is a condensed version of two talks I gave to the Minneapolis Perl Mongers, which are available online at http://www.indecorous.com/perl/.
perlobj
The Perl objects reference page. Available via http://search.cpan.org/perldoc?perlobj or perldoc perlobj.
perltoot
Tom Christiansen's object oriented Perl tutorial. Available via http://search.cpan.org/perldoc?perltoot or perldoc perltoot.
Object Oriented Perl
Object Oriented Perl, by Damian Conway, is probably the best book on the subject. Available from http://www.amazon.com/dp/1884777791 and all good bookshops.