Solution Review: Calculating Area

Let's go over the solution review of the challenge given in the previous lesson.

We'll cover the following

Let’s look at the solution first before jumping into the explanation:

Press + to interact
package Triangle; # class name
sub new {
my $class = shift;
my $self = {
_length => shift,
_height => shift,
};
# Print all the values just for clarification.
print "Length is $self->{_length}\n";
print "Height is $self->{_height}\n";
bless $self, $class;
return $self;
}
sub area{
my ($self) = @_;
return ($self->{_length} * $self->{_height}) / 2;
}
1;
$object = new Triangle( 4, 5);
print "Area of Triangle: " . $object->area();

Explanation

Line 1:

  • We have initialized the package Triangle.

Line 3 - 17:

  • We have defined the constructor and declared the class member variables _length and _height. We shifted the values so that for every object of the class, we can use a new set of variables.

Line 19 - 24:

  • We have defined area subroutine which is called in line 27 from the main,