Quick and Dirty Intro to Perl Objects

November 18th, 2006

Although 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.

  1. 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.
  2. Perl uses $self as the reference that most people will know as 'this'.
  3. To create a new object the call is generally: my $obj = MyClass->new(); rather than my $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

Comments

You can be the first to comment!

Post your own comment
  • This comment form supports limited Markdown entry.
  • Please wrap code examples in <pre><code>
  • Please note that your e-mail will not be displayed on this page. We will never pass on your details and your information will be kept private.
Back to top