Search⌘ K

Solution Review: Calculating Area

Explore how to create and use a Perl package named Triangle. Learn to set member variables with a constructor and calculate the area using a subroutine for object-oriented programming.

We'll cover the following...

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

Perl
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,