Defining Class Methods in Perl

PERLServer Side ProgrammingProgramming Scripts

Other object-oriented languages have the concept of security of data to prevent a programmer from changing an object data directly and they provide accessor methods to modify object data. Perl does not have private variables but we can still use the concept of helper methods to manipulate object data.

Lets define a helper method to get person’s first name −

sub getFirstName {
   return $self->{_firstName};
}

Another helper function to set person’s first name −

sub setFirstName {
   my ( $self, $firstName ) = @_;
   $self->{_firstName} = $firstName if defined($firstName);
   return $self->{_firstName};
}

Now lets have a look into complete example: Keep Person package and helper functions into Person.pm file.

#!/usr/bin/perl
package Person;
sub new {
   my $class = shift;
   my $self = {
      _firstName => shift,
      _lastName => shift,
      _ssn => shift,
   };
   # Print all the values just for clarification.
   print "First Name is $self->{_firstName}\n";
   print "Last Name is $self->{_lastName}\n";
   print "SSN is $self->{_ssn}\n";
   bless $self, $class;
   return $self;
}
sub setFirstName {
   my ( $self, $firstName ) = @_;
   $self->{_firstName} = $firstName if defined($firstName);
   return $self->{_firstName};
}
sub getFirstName {
   my( $self ) = @_;
   return $self->{_firstName};
}
1;

Now let's make use of Person object in employee.pl file as follows −

#!/usr/bin/perl
use Person;
$object = new Person( "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 "Before 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
Before Setting First Name is : Mohammad
Before Setting First Name is : Mohd.
raja
Published on 02-Dec-2019 12:02:13
Advertisements