Creating and Using Objects using Perl


To create an instance of a class (an object) we need an object constructor in Perl. This constructor in Perl is a method defined within the package. Most programmers choose to name this object constructor method new, but in Perl you can use any name.

You can use any kind of Perl variable as an object in Perl. Most Perl programmers choose either references to arrays or hashes.

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. For example −

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;
}

Now Let us see how to create an Object.

$object = new Person( "Mohammad", "Saleem", 23234345);

You can use simple hash in your consturctor if you don't want to assign any value to any class variable. For example −

package Person;
sub new {
   my $class = shift;
   my $self = {};
   bless $self, $class;
   return $self;
}

Updated on: 02-Dec-2019

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements