The Wayback Machine - https://web.archive.org/web/20240927202108/https://www.geeksforgeeks.org/perl-objects-in-oops/
Open In App

Perl | Objects in OOPs

Last Updated : 13 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Perl is a high-level, general-purpose programming language that was originally designed for text manipulation and system administration tasks. It was created in the late 1980s by Larry Wall and has since evolved into a popular language for a wide range of applications, including web development, network programming, and data analysis.

Perl is known for its flexibility, expressive syntax, and powerful string manipulation capabilities. It supports both procedural and object-oriented programming paradigms, and includes a wide range of built-in functions and modules that make it easy to handle complex tasks.

One of the key features of Perl is its regular expression support, which allows for advanced text processing and pattern matching. Perl also has a large and active community of developers who contribute to the language’s development and support its various modules and tools.

Overall, Perl is a versatile and powerful language that can be used for a wide range of programming tasks, particularly those involving text and data processing.

package Employee;

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’. 

PERL




package Employee;
 
# Constructor with name new
sub new
{
    my $class = shift;
    my $self = {
                  _serialNum => shift,
                  _firstName => shift,
                  _lastName  => shift,
              };
     
    bless $self, $class;
    return $self;
}


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: 

perl




use strict;
use warnings;
 
# class with the name Employee
package Employee;
 
# constructor with the name new
sub new
{           
    # shift will take package name
    # and assign it to variable 'class'
    my $class = shift;   
     
    # defining the hash reference
    my $self = {                        
                _serialNum => shift,
                _firstName => shift,
                _lastName => shift,
               };
     
    # Attaching object with class
    bless $self, $class;
     
    # returning the instance of class Employee
    return $self;                        
}
 
# Object creation of the class
my $object = new Employee(1, "Geeks", "forGeeks");
 
# object here is a hash to a reference
print("$object->{_firstName} \n");            
print("$object->{_serialNum} \n");   


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.

In Perl, objects are instances of classes. A class is a blueprint or a template for creating objects, which defines a set of attributes (properties) and methods (functions) that the objects of that class can have.

Here’s an example code that demonstrates the creation of a class and the creation of objects from that class:

Perl




#!/usr/bin/perl
# your code here
# Define a class called "Person"
package Person;
 
# Define the constructor method for the class
sub new {
    my $class = shift;
    my $self = {
        name => shift,
        age => shift,
        gender => shift,
    };
    bless $self, $class;
    return $self;
}
 
# Define a method for the class that returns the person's name
sub get_name {
    my ($self) = @_;
    return $self->{name};
}
 
# Define a method for the class that returns the person's age
sub get_age {
    my ($self) = @_;
    return $self->{age};
}
 
# Define a method for the class that returns the person's gender
sub get_gender {
    my ($self) = @_;
    return $self->{gender};
}
 
# Create two objects of the "Person" class
my $person1 = new Person("John", 25, "Male");
my $person2 = new Person("Jane", 30, "Female");
 
# Print the properties of the objects to the console
print "Person 1: " . $person1->get_name() . ", " . $person1->get_age() . ", " . $person1->get_gender() . "\n";
print "Person 2: " . $person2->get_name() . ", " . $person2->get_age() . ", " . $person2->get_gender() . "\n";


Output

Person 1: John, 25, Male
Person 2: Jane, 30, Female

In this code, a class called “Person” is defined using the package keyword. The new() method is defined as the constructor for the class, which initializes a new object of the class with the given properties. Three properties (name, age, and gender) are defined for the objects, which are passed as arguments to the constructor method.

Three methods (get_name(), get_age(), and get_gender()) are also defined for the class, which return the corresponding property value for an object of the class.

Two objects ($person1 and $person2) are then created from the Person class using the new() method, and their properties are printed to the console using the get_name(), get_age(), and get_gender() methods.



Previous Article
Next Article

Similar Reads

Perl | Inheritance in OOPs
Inheritance is a key concept in object-oriented programming that allows you to define a new class based on an existing class. The new class, called a subclass or derived class, inherits all of the properties and methods of the existing class, called the superclass or base class, and can also define its own unique properties and methods. In Perl, in
7 min read
Perl | Method Overriding in OOPs
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method
6 min read
Perl | Polymorphism in OOPs
Polymorphism is the ability of any data to be processed in more than one form. The word itself indicates the meaning as poly means many and morphism means types. Polymorphism is one of the most important concepts of object-oriented programming languages. The most common use of polymorphism in object-oriented programming occurs when a parent class r
5 min read
Object Oriented Programming (OOPs) in Perl
Object-oriented programming: As the name suggests, Object-Oriented Programming or OOPs refers to languages that uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on
7 min read
Perl | Methods in OOPs
Methods are used to access and modify the data of an object. These are the entities which are invoked with the use of objects of a class or a package itself. Methods are basically a subroutine in Perl, there is no special identity of a method. Syntax of a method is the same as that of a subroutine. Just like subroutines, methods are declared with t
5 min read
Perl | Encapsulation in OOPs
Encapsulation in Perl is the process of wrapping up of data to protect it from the outside sources which need not have access to that part of the code. Encapsulation is a part of the Object-oriented programming, it is used to bind the data and the subroutines that are used to manipulate that data. In a different way, encapsulation is a protective s
6 min read
Perl | Basic Syntax of a Perl Program
Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar
10 min read
Perl | chomp() Function
The chomp() function in Perl is used to remove the last trailing newline from the input string. Syntax: chomp(String) Parameters: String : Input String whose trailing newline is to be removed Returns: the total number of trailing newlines removed from all its arguments Example 1: C/C++ Code #!/usr/bin/perl # Initialising a string $string = &quo
2 min read
Perl | Backtracking in Regular Expression
In Perl, a Regular expression(a.k.a regexes or regexps or REs) is a way of describing a set of strings without having to list all strings in your program or simply we can say that it is a sequence of characters that are used for pattern matching. In Perl, regular expressions have different uses: Firstly, they are used in conditionals to determine w
3 min read
Perl | Searching in a File using regex
Prerequisite: Perl | Regular Expressions Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to host language and are not the same as in PHP, Python, etc. Sometimes these are termed as "Perl 5 Compatible Regular Expressions". To use the Regex, Bindi
6 min read
Perl | Operators | Set - 1
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Operators Can be categorized based upon their different functionality: Arithmetic OperatorsRelat
12 min read
Perl | lt operator
'lt' operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise less than the string to its right. Syntax: String1 lt String2 Returns: 1 if left argument is less than the right argument Example 1: #!/usr/local/bin/perl # Initializing Strin
1 min read
Perl | chop() Function
The chop() function in Perl is used to remove the last character from the input string. Syntax: chop(String) Parameters: String : It is the input string whose last characters are removed. Returns: the last removed character. Example 1: #!/usr/bin/perl # Initialising a string $string = "GfG is a computer science portal"; # Calling the chop
1 min read
Perl | rename() Function
rename() function in Perl renames the old name of a file to a new name as given by the user. Syntax: rename(old_file_path, new_file_path) Parameters: old_file_path: path of the old file along with its name new_file_path: path of the new file along with its name Returns 0 on failure and 1 on success Example: #!/usr/bin/perl -w # Calling the rename()
1 min read
Perl | Subroutines or Functions
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in s
2 min read
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance
6 min read
Perl | Loops (for, foreach, while, do...while, until, Nested loops)
Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the program. The loops in Perl are : for Loop "for" loop
7 min read
Perl | Comparing Scalars
Prerequisite: Scalars in Perl Perl has two types of comparison operator sets. Just like other mathematical operators, instead of performing operations, these operators compare scalars. There are two types of sets of Perl comparison operators. One is for numeric scalar values and one is for string scalar values. Both the types are illustrated in bel
6 min read
Perl | String functions (length, lc, uc, index, rindex)
String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follows: length() lc() uc() index() rindex() length(): T
4 min read
Perl | Arrays
In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Example: @number = (50, 70, 46); @names = ("Geeks", "For", "Geeks"); Array Creation: In Perl programming ever
6 min read
Perl | Data Types
Data types specify the type of data that a valid Perl variable can hold. Perl is a loosely typed language. There is no need to specify a type for the data while using in the Perl program. The Perl interpreter will choose the type based on the context of the data itself. There are 3 data types in Perl as follows: ScalarsArraysHashes(Associative Arra
3 min read
Perl | String Operators
Operators are the foundation of any programming language. Thus, the functionality of Perl programming language is incomplete without the use of operators. A user can define operators as symbols that help to perform specific mathematical and logical computations on operands. String are scalar variables and start with ($) sign in Perl. The String is
4 min read
Perl | Hashes
Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. The variable name is preceded by the dollar sign($)followed by key under curly braces and the value as
5 min read
Perl | Regular Expressions
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“. To use the Regex, Binding operators like ‘=~‘(Regex Operator) and
2 min read
Perl | Regex Cheat Sheet
Regex or Regular Expressions are an important part of Perl Programming. It is used for searching the specified text pattern. In this, set of characters together form the search pattern. It is also known as regexp. When user learns regular expression then there might be a need for quick look of those concepts which he didn't use often. So to provide
6 min read
Introduction to Perl
Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used expansion is "Practical Extraction and Reporting Language". Some of the programmers also refer Perl as the "Pathologically Eclectic Rubbish Lister" Or "Prac
9 min read
Perl | Regex Character Classes
Character classes are used to match the string of characters. These classes let the user match any range of characters, which user don’t know in advance. Set of characters that to be matched is always written between the square bracket []. A character class will always match exactly for one character. If match not found then the whole regex matchin
3 min read
Perl | Special Character Classes in Regular Expressions
There are many different character classes implemented in Perl and some of them used so frequently that a special sequence is created for them. The aim of creating a special sequence is to make the code more readable and shorter. The Special Character Classes in Perl are as follows: Digit \d[0-9]: The \d is used to match any digit character and its
4 min read
Perl | Subroutines or Functions | Set - 2
Prerequisite: Subroutines or Functions in Perl A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In this article we will di
4 min read
Perl | Operators | Set - 2
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Some of the operators already discussed in Perl Operators Set - 1. Remaining operators will be d
7 min read
Article Tags :