Main Content

Building an object based on another object in Perl

Archive - Originally posted on "The Horse's Mouth" - 2012-12-03 18:17:04 - Graham Ellis

When you create an object, you call a constructor method. In many languages, there's a special name for this method and the word new or init is often involved ... so in Perl it's a good convention to use new as well.

Example:
  $first = new roundtable(1800,"Pine");

Where does Perl find the new method?

Firstly, it will look for a sub called new in the roundtable package. If there isn't one, it will look in any packages which roundtable inherits from by looking in the list @ISA, and it will recursively explore all parent packages until it finds a new sub.

If no new sub is available, the same traversal will be applied looking for a sub called AUTOLOAD. And if that fails too, then an error / excpetion is thrown.

How does Perl run two new methods?

There are occasions when you'll want to construct an object and within its constrcutor call the constructor of its base class. This is the super call in Python, and you may be familiar with other ways of doing this in other languages - it's pretty nonstandard.

In Perl, you can call the constructor of the parent class, and the
re-bless the resulting reference into the subclass. Here's an example, where a roundtable is based on a table but with a single extra parameter.

table constructor:

  sub new {
    my ($type,$mat) = @_;
    my %self;
    $self{m} = $mat;
    bless \%self,$type;
    }


roundtable constructor which calls in table constructor:

  sub new {
    my ($type, $diam, $material) = @_;
    my $this = new table($material);
    $this->{h} = $diam;
    bless $this,$type;
    }


Complete, working example (also shows AUTOLOAD in use) [here] from last week's Perl Course.