5.6.2.1 Defining a Constructor Method

5.6.2.1  Defining a Constructor Method

  Let us look at the constructor method make in the Person class. It has two lexically scoped scalars: $self and $class. $self is assigned a reference to the empty hash that is going to store the object instance being created. $class stores the name of the class whose instance is being created. The value of $class comes from the call to the make method. Instances of class Person contain only one field or slot or property: name. The value of the name
slot is given the value undef at initialization. Next, the make method calls a pompously named built-in function bless that takes two arguments: a reference to an instance being created, and the class to which this instance belongs. bless anoints the reference variable as a reference to an instance of the named class. In creating an instance of a class, the bless function must always be used. The blessed data structure
which is an anonymous hash still remains a hash, but additionally becomes an instance of the class under consideration. Finally, the make method returns a reference to the instance that was created. As an example, in the program, we create an empty instance of the class Person called $erin in the main package by making the call

 

$erin = Person -> make;

 

Here, the method make of the class Person is being called with one argument which is the string ’Person’. The syntax is a little unusual in that the argument ’Person’ is not written down explicitly. The same call could have been made as

 

$erin = Person::make ('Person');

 

with exactly the same meaning. The -> operator provides a shortcut for writing calls to methods. -> is an infix operator. It has the class name on the left side and the name of a method for the class on the right side. The first argument of the method is implicitly assumed to be the name of the class in string form. In this specific instance, when we use the -> syntax call to make there is no explicit argument, but ’Person’ is assumed to be the implicit first argument anyway.