Unlike many other languages, Perl does not have constructors that allocate memory for your objects. Instead, one should write a class method that both create a data structure and populate it with data (you may know it as the Factory Method design pattern).
package Point;
use strict;
sub new {
my ($class, $x, $y) = @_;
my $self = { x => $x, y => $y }; # store object data in a hash
bless $self, $class; # bind the hash to the class
return $self;
}
This method can be used as follows:
my $point = Point->new(1, 2.5);
Whenever the arrow operator ->
is used with methods, its left operand is prepended to the given argument list. So, @_
in new
will contain values ('Point', 1, 2.5)
.
There is nothing special in the name new
. You can call the factory methods as you prefer.
There is nothing special in hashes. You could do the same in the following way:
package Point;
use strict;
sub new {
my ($class, @coord) = @_;
my $self = \@coord;
bless $self, $class;
return $self;
}
In general, any reference may be an object, even a scalar reference. But most often, hashes are the most convenient way to represent object data.