Quick and Dirty Intro to Perl Objects
November 18th, 2006Although I've been writing Perl for a long time, OO Perl (also known as Poop!) has been remained somewhat of a mystery to me.
On first inspection it doesn't resemble any typical OO language, but if you scratch a little under the surface, you'll see there's nothing really to them.
This tutorial assumes you have an understanding of Perl and have a basic grasp of object orientated programming, but want a quick step introduction to Perl objects.
Example Class
If you know a little about OO, then you'll recognise pretty much all of this code with the exception of the new function.
use strict; # strict error handling
package MyClass; # the class name
sub new
{
# get a reference to the object
# class from the implicit @_ variable
my $class = shift;
# collect the parameters passed in via a hash
my %params = @_;
# bind the class methods and attributes
# to $self using bless
my $self = {};
bless $self, $class;
# arbitrary start up functions - always referring
# to $self to change the state of our object
$self->setValue(%params{'value'} || '13');
# return the reference to the object
return $self;
}
# class methods
sub setValue
{
my $self = shift; # reference to object instance
$self->{'my_value'} = shift;
}
sub timesTen
{
my $self = shift;
return $self->{'my_value'} * 10;
}
Example Usage
#!/usr/local/bin/perl
use strict;
# create a new instance of 'MyClass'
my $obj = MyClass->new(value => 13);
# simple example of method execution
print $obj->timesTen();
print " ";
$obj->setValue(35);
print $obj->timesTen();
print " ";
# Output of script:
# > 130
# > 350
Conventions
There's a few conventions used by Perl OO.
- Packages (aka class names) are written in title case with no underscores, e.g. MyReallyCoolClass. If the class resides in a sub directory, the naming conventions follow and the paths are separated by '::', e.g. GenericClasses::MyReallyCoolClass.
- Perl uses $self as the reference that most people will know as 'this'.
- To create a new object the call is generally:
my $obj = MyClass->new();rather thanmy $obj = new MyClass;
Further Reading
- Perl Objects on search.cpan.org
- Perl function list by category
- Object-oriented tutorial for perl: from the command line, type: perldoc perltoot

You can be the first to comment!