O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Constructing an Object

Problem

You want to create a way for your users to generate new objects.

Solution

Make a constructor. In Perl, the constructor method must not only initialize its object, but must also first allocate memory for it, typically using an anonymous hash. C++ constructors, on the other hand, are called with memory already allocated. The rest of the object-oriented world would call C++’s constructors initializers .

Here’s the canonical object constructor in Perl:

sub new {
    my $class = shift;
    my $self  = { };
    bless($self, $class);
    return $self;
}

This is the equivalent one-liner:

sub new { bless( { }, shift ) }

Discussion

Any method that allocates and initializes a new object acts as a constructor. The most important thing to remember is that a reference isn’t an object until bless has been called on it. The simplest possible constructor, although not particularly useful, is the following:

sub new { bless({}) }

Let’s add some initialization:

sub new {
    my $self = { };  # allocate anonymous hash
    bless($self);
    # init two sample attributes/data members/fields
    $self->{START} = time();  
    $self->{AGE}   = 0;
    return $self;
}

This constructor isn’t very useful because it uses the single-argument form of bless, which always blesses the object into the current package. This means it can’t be usefully inherited from; objects it constructs will always be blessed into the class that the new function was compiled into. In the case of inheritance, this is not necessarily the class on whose behalf ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required