The Object Oriented concept in Perl is very much based on references and anonymous array and hashes. Let's start learning basic concepts of Object Oriented Perl.
Object Basics
In Perl, a package is a self-contained unit of user-defined variables and subroutines, which can be re-used over and over again. Perl Packages provide a separate namespace within a Perl program which keeps subroutines and variables independent from conflicting with those in other packages.
To declare a class named Person in Perl we do:
package Person;
Let's create our constructor for our Person class using a Perl hash reference. When creating an object, you need to supply a constructor, which is a subroutine within a package that returns an object reference. The object reference is created by blessing a reference to the package's class.
#!/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 scientific-employee.pl
file as follows:
#!/usr/bin/perl
use Person;
$object = new Person( "Sci", "Pro", 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( "Scientific" );
# 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 Scientific
Last Name is Pro
SSN is 124567890
Before Setting First Name is : Sci
Before Setting First Name is : Pro.
Run interactively!
The "PERL Systems & Scientific Programming Course" is a hands-on training that will give you a solid understanding and practical knowledge of Perl in order to be able to build any project.
https://school.scientificprogramming.io/home/course/perl-systems-scientific-programming/17
Top comments (0)