Constructor (object-oriented Programming) - Perl

Perl

In Perl version 5, by default, constructors must provide code to create the object (a reference, usually a hash reference, but sometimes an array reference, scalar reference or code reference) and bless it into the correct class. By convention the constructor is named new, but it is not required, or required to be the only one. For example, a Person class may have a constructor named new as well as a constructor new_from_file which reads a file for Person attributes, and new_from_person which uses another Person object as a template.

package Person; use strict; use warnings; # constructor sub new { # class name is passed in as 0th # argument my $class = shift; # check if the arguments to the # constructor are key => value pairs die "$class needs arguments as key => value pairs" unless (@_ % 2 == 0); # default arguments my %defaults; # create object as combination of default # values and arguments passed my $obj = { %defaults, @_, }; # check for required arguments die "Need first_name and last_name for Person" unless ($obj->{first_name} and $obj->{last_name}); # any custom checks of data if ($obj->{age} && $obj->{age} < 18)) { # no under-18s die "No under-18 Persons"; } # return object blessed into Person class bless $obj, $class; } 1;

Read more about this topic:  Constructor (object-oriented Programming)