Perl is an Objected Oriented, dynamic and interpreter based programming language. In object-oriented programming, we have three main aspects, which are, object, class, and methods. An object is a data type which can be specifically called as an instance of the class to which it belongs. It can be a collection of data variables of different data types and as well as a collection of different data structures. Methods are functions which work on these objects of the class.
Following is a basic example to better understand how objects can be used in Perl:
First, we need to define the class. In Perl, it is done by building the package of the class. Package is an encapsulated entity which has all the data members and the methods of the concerned class.
Here, Employee is the class name.
Second task, is to create an instance of the package(i.e the object). For this, we need a constructor. A constructor is a subroutine in Perl which generally is given the name ‘new’. However, the name is user defined hence not restricted to ‘new’.
In the constructor we are defining a simple hash reference $self to design our object. Here, the object will have three values serialNum, firstName, and lastName of an Employee, which means every employee concerned to this will have their own set of serial number, firstname, and lastname. The
my keyword is an access specifier which is localizing $class and $self to be within the enclosed block.
shift keyword takes the package name from the default array “@_” and pass it on to the bless function.
bless function is used to return a reference which ultimately becomes an object.
And in the end, the constructor will finally return the instance of the class Employee(here).
Finally, the main part is how to initialize an object. It can be done in the following way:
$object = new Employee(1, "Geeks", "forGeeks");
Here, $object is a scalar variable which is a reference to the hash defined in the constructor.
Following is the example program for the creation and implementation of Objects in OOPs:
An object in Perl works in the same way as in other languages like C++, Java, etc. Above program shows the working of an object in Perl, its creation and its use in the class.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.