Method Overriding in Perl

You can add your additional functions in child class or you can add or modify the functionality of an existing methods in its parent class. It can be done as follows −

package Employee;
use Person;
use strict;
our @ISA = qw(Person);    # inherits from Person
# Override constructor
sub new {
   my ($class) = @_;
   # Call the constructor of the parent class, Person.
   my $self = $class->SUPER::new( $_[1], $_[2], $_[3] );
   # Add few more attributes
   $self->{_id} = undef;
   $self->{_title} = undef;
   bless $self, $class;
   return $self;
# Override helper function
sub getFirstName {
   my( $self ) = @_;
   # This is child class function.
   print "This is child class helper function\n";
   return $self->{_firstName};
# Add more methods
sub setLastName{
   my ( $self, $lastName ) = @_;
   $self->{_lastName} = $lastName if defined($lastName);
   return $self->{_lastName};
sub getLastName {
   my( $self ) = @_;
   return $self->{_lastName};

Now let's again try to use Employee object in our file and execute it.

use Employee;
$object = new Employee( "Mohammad", "Saleem", 23234345);
# Get first name which is set using constructor.
$firstName = $object->getFirstName();
print "Before Setting First Name is : $firstName\n";
# Now Set first name using helper function.
$object->setFirstName( "Mohd." );
# Now get first name set by helper function.
$firstName = $object->getFirstName();
print "After Setting First Name is : $firstName\n";

When we execute above program, it produces the following result −

First Name is Mohammad
Last Name is Saleem
SSN is 23234345
This is child class helper function
Before Setting First Name is : Mohammad
This is child class helper function
After Setting First Name is : Mohd.