The Wayback Machine - https://web.archive.org/web/20241004173640/https://www.geeksforgeeks.org/perl-classes-in-oop/
Open In App

Perl | Classes in OOP

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

In this modern world, where the use of programming has moved to its maximum and has its application in each and every work of our lives, we need to adapt ourselves to such programming paradigms that are directly linked to the real-world examples. There has been a drastic change in the competitiveness and the complexity of the real-world problems, thus the industry now requires some versatile approaches towards these complexities. The concept of Object-Oriented Programming language copes up comfortably with these complexities and is a perfect way of shaping up any programming language in a way that the real-world examples become very easy to solve. Object-Oriented Programming(OOP) uses the methodology of emphasizing more on objects rather than the procedure. The OOPs concept is about working in terms of objects and the interaction between objects. 

Note: Object-oriented programming aims to implement real-world entities like inheritance, encapsulation, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.

Object –

An object is an instance of a class of the data structure with some characteristics and behavior. For Example, we say an “Apple” is an object. Its characteristics are:it is a fruit, its color is red, etc. Its behavior is:”it tastes good“. In the concept of OOPs, the characteristics of an object are represented by its data and the behavior is represented by its associated functions. Thus an object is an entity that stores data and has its interface through functions.

Class –

A class is an expanded concept of data structures. It defines a prototype blueprint of objects comprising of data. And an object is an instance of a class. A class comprises of the data members and data functions and it is a pre-defined data type made as per the user’s requirements which can be accessed and used by creating an instance of that class.

Example: 
Consider a class of School. There may be schools with different names and structure but all of them share some common characteristics like students, teachers, staff, etc. So here school is the class with teachers, students, and Parents as the data members, and the member functions can be calculate_students_marks(), calculate_teachers_salary(), and Parents_Database(). 

Data Member: Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions define the properties and behavior of the objects in a Class. 

Defining a Class –

It is very easy to define a class in Perl. In Perl, a Class corresponds to a package. To define a class we first load and build a Package. A Package is a pre-contained unit of user-defined variables and subroutines, which can be used throughout the program.

Syntax:  

package Class_name

Creating Class and Using Objects

A class in Perl can be created by using the keyword package but to create an object, a constructor is called. A constructor is defined in a class as a method. 

Creating an instance of a class 
A class name and a constructor name can be as per user’s requirement. Most of the programmers prefer to use ‘new’ as a constructor name for their programs as it is easy to remember and is more feasible to use than any other complex constructor name.  

Perl




package student     // This is the class student
sub Student_data    // Constructor to class
{
    my $class = shift;
    my $self = {
                _StudentFirstName => shift;
                _StudentLastName => shift;
               };
                
    print "Student's First Name is $self ->{_StudentFirstName}\n";
    print "Student's Last Name is $self ->{_StudentLastName}\n";
    bless $self, $class;
    return $self;
}


In the above example code, a function named bless is used. This function is used to attach an object to a class which is passed to it as an argument. 

Syntax: 

bless Object_name, Class Name

Creating an Object 
An object in Perl is instantiated by using the constructor defined in the class. An object name can be any variable as per user’s requirement, but it is conventional to name it with respect to the relevancy with the class.  

Perl




$Data = Student_data student( "Shikhar", "Mathur");


Example: 

Perl




use strict;
use warnings;
 
package student;
 
# constructor
sub student_data
{
 
    # shift will take package name 'student'
    # and assign it to variable 'class'
    my $class_name = shift;
    my $self = {
                'StudentFirstName' => shift,
                'StudentLastName' => shift
               };
    # Using bless function
    bless $self, $class_name;
     
    # returning object from constructor
    return $self;
}
 
# Object creating and constructor calling
my $Data = new student_data student("Geeks","forGeeks");
 
# Printing the data
print "$Data->{'StudentFirstName'}\n";
print "$Data->{'StudentLastName'}\n";


The concept of using classes in Object-Oriented Programming is very important as it completely depicts the real-world applications and can be adopted in real-world problems.
 

In Perl, classes can be defined using the package keyword, which is used to define a namespace for variables, subroutines, and other code constructs. Here’s an example of defining a class in Perl:

Perl




# Define the Person class
package Person;
 
# Constructor method to create a new object of the class
sub new {
    my $class = shift;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    # Bless the reference as an object of the class
    bless $self, $class;
    return $self;
}
 
# Accessor method to get the first name of the person
sub getFirstName {
    my ($self) = @_;
    return $self->{_firstName};
}
 
# Accessor method to set the first name of the person
sub setFirstName {
    my ($self, $firstName) = @_;
    $self->{_firstName} = $firstName if defined($firstName);
    return $self->{_firstName};
}
 
# End of package declaration, required in Perl
1;
 
# Use the Person class
use Person;
 
# Create a new object of the Person class
my $person = Person->new("John", "Doe", "123-45-6789");
 
# Call the getFirstName method to get the first name of the person
my $firstName = $person->getFirstName();
print "First name: $firstName\n";
 
# Call the setFirstName method to change the person's first name
$person->setFirstName("Jane");
$firstName = $person->getFirstName();
print "New first name: $firstName\n";


Output:

First name: John
New first name: Jane

This code creates a new Person object with the properties firstName (set to “John”), lastName (set to “Doe”), and ssn (set to “123-45-6789”). It then calls the getFirstName() method to get the person’s first name and prints it to the console.

Next, it calls the setFirstName() method to change the person’s first name to “Jane”. It then calls getFirstName() again to get the person’s new first name and prints it to the console.



Previous Article
Next Article

Similar Reads

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 | 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 | 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 | 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
Perl | qw Operator
The qw operator in Perl is used to extract each element of the given string as it is in an array of elements in single-quote ( ' ' ). This function stands for quote word because it considers each word of the given string as it is quoted like qw(Geeks for Geeks) is equivalent to ('Geeks', 'for', 'Geeks'). This qw() uses parentheses so it seems like
2 min read
Perl | Reverse an array
Reverse an array or string in Perl. Iterative Way: Iterate over the array from 0 to mid of array. Swap the arr[i] element with arr[size-i] element. #Perl code to reverse an array iteratively #declaring an array of integers @arr = (2, 3, 4, 5, 6, 7); # Store length on array in $n variable $n = $#arr; #Print the original array print "The origina
2 min read
Packages in Perl
A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension .pm. Two different modules may contain a variable or a function of the same name. Any variable which is not contained in any package belongs to the main package. There
4 min read
Perl | Scope of Variables
The scope of a variable is the part of the program where the variable is accessible. A scope is also termed as the visibility of the variables in a program. In Perl, we can declare either Global variables or Private variables. Private variables are also known as lexical variables. Scope of Global Variables Global variables can be used inside any fu
6 min read
Perl | References
In Perl, we use variables to access data stored in a memory location(all data and functions are stored in memory). Variables are assigned with data values that are used in various operations. Perl Reference is a way to access the same data but with a different variable. A reference in Perl is a scalar data type that holds the location of another va
4 min read
Perl | Math::BigInt->digit() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. digit() method of Math::BigInt module is used to get nth digit of the given number counting from right. To get the digit from the left side we need to specify n as negative. Syntax: Math::BigInt->digit($n) Paramete
3 min read
Article Tags :