Perl Constructor Tutorial

During all of my years of perl development, I really got used to using the constructor style used by many modules on CPAN, that is, I loved being able to instantiate a module like this:

my $newObject = MyClass->new( arg1 => "firstarg", arg2 => "secondarg");

I like this style because it compresses code into one line instead of calling methods to specify the args like this:

my $newObject = MyClass->new();
$newObject->arg1("firstarg");
$newObject->arg2("secondarg");

So I decided that I would write a perl constructor template that I could reuse during perl module development.

The main features I would look for in a constructor in any language are the following:

  1. Supports the inline arguments as explained above.
  2. Supports the copy constructor.
  3. Supports default arguments that you can define inside of your module.
  4. The inline arguments are allowed to override the default arguments.

So with these goals in mind, here is the constructor template that I use in my perl modules:

# default arguments
my %fields = ( arg1 => 0, arg2 => undef,);

sub new {
  my $that = shift;
  my $class = ref($that) || $that;
  my $self = {};
  if(ref($that)) { # copy
    %$self = %$that;
  }
  else { # new
    # the default arguments are defined in the $self object including %fields
    # the @_ brings in the inline arguments passed to the function
    # listing @_ after %fields will override %fields defaults
    $self = { %fields, @_, };
  }
  bless $self, $class;
  return $self;
}

Please see the comments inline above for the best description of the constructor template, and feel free to use it in your perl module projects.