Object Oriented Programming (OOPs) in Perl Last Updated : 12 Jul, 2025 Comments Improve Suggest changes Like Article Like Report 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 them so that no other part of the code can access this data except that function. OOPs Concepts: ClassObjectMethodPolymorphismInheritanceEncapsulationAbstraction Let us learn about the different characteristics of an Object Oriented Programming language: Class: A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:Class name: The name should begin with a initial letter (capitalized by convention).Superclass(if any): The name of the class's parent (superclass), if any, preceded by the keyword 'use'.Constructors(if any):Constructors in Perl subroutines returns an object which is an instance of the class. In Perl, the convention is to name the constructor “new”.Body: The class body surrounded by braces, { }.Object: It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Perl program creates many objects, which as you know, interact by invoking methods. An object consists of :State : It is represented by attributes of an object. It also reflects the properties of an object.Behavior : It is represented by methods of an object. It also reflects the response of an object with other objects.Identity : It gives a unique name to an object and enables one object to interact with other objects.Method: A method is a collection of statements that perform some specific task and return result to the caller. A method can perform some specific task without returning anything. Methods are time savers and help us to reuse the code without retyping the code.Polymorphism: Polymorphism refers to the ability of OOPs programming languages to differentiate between entities with the same name efficiently. This is done by Perl with the help of the signature and declaration of these entities. Polymorphism in Perl are mainly of 2 types:Overloading in PerlOverriding in PerlInheritance: Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in perl by which one class is allowed to inherit the features(fields and methods) of another class. Important terminology:Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class).Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.Reusability: Inheritance supports the concept of "reusability", i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared.As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.Encapsulation can be achieved by: Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.Abstraction: Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components. Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects. Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes, etc in the car. This is what abstraction is.here's an example of a simple Perl class and object: Perl # Define a class named Person package Person; 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; } sub getFirstName { my ($self) = @_; return $self->{_firstName}; } sub setFirstName { my ($self, $firstName) = @_; $self->{_firstName} = $firstName if defined($firstName); return $self->{_firstName}; } 1; # End of package declaration, required in Perl # Create a new Person object 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"; OutputFirst name: John New first name: Jane This program 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. Here are some benefits of using Object-Oriented Programming (OOP) in Perl:Code reusability: OOP allows you to define reusable classes that can be used in multiple parts of your program. This reduces the amount of code you need to write and makes your program more modular and maintainable.Encapsulation: OOP allows you to encapsulate data and behavior within classes, which helps prevent accidental modification of data from outside the class. This also makes it easier to change the implementation details of a class without affecting the rest of the program.Inheritance: Perl supports inheritance, which allows you to define a new class based on an existing class. This is useful when you want to create a new class that has similar behavior to an existing class but with some additional features.Polymorphism: OOP allows you to define methods with the same name in different classes, and the appropriate method will be called based on the object's class. This makes it easier to write generic code that works with different types of objects.Modularization: OOP encourages modular design by allowing you to split your program into smaller, more manageable classes. This makes it easier to understand and maintain large programs. Overall, OOP in Perl can make your programs more modular, maintainable, and extensible. It provides a powerful set of tools for organizing and structuring your code, and it can help you write cleaner, more elegant programs. Comment More infoAdvertise with us Next Article Introduction to Perl A Abhinav96 Follow Improve Article Tags : Perl Perl-OOP Similar Reads BasicsPerl Programming LanguagePerl is a general purpose, high level interpreted and dynamic programming language. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++. Since Perl is a lot similar to other widely used lan3 min readIntroduction to PerlPerl 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 the9 min readPerl Installation and Environment Setup in Windows, Linux, and MacOSPrerequisite: Introduction to Perl Before, we start with the process of Installing Perl on our System, whether it be Windows, Linux or Macintosh. We must have first-hand knowledge of What the Perl Language is and what it actually does?. Perl is a general purpose, high level interpreted and dynamic p3 min readPerl | Basic Syntax of a Perl ProgramPerl 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 and10 min readHello World Program in PerlPerl programming language is exclusively designed for text processing purposes. Its abbreviation denotes Practical Extraction and Report Language. It is compatible on various platforms, such as Windows, Mac OS, and almost all versions of UNIX. Hello World! program in every programming language gives3 min readFundamentalsPerl | Data TypesData 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 Pe3 min readPerl | Boolean ValuesIn most of the programming language True and False are considered as the boolean values. But Perl does not provide the type boolean for True and False. In general, a programmer can use the term "boolean" when a function returns either True or False. Like conditional statements(if, while, etc.) will3 min readPerl | Operators | Set - 1Operators 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 their12 min readPerl | Operators | Set - 2Operators 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 Per7 min readPerl | VariablesVariables in Perl are used to store and manipulate data throughout the program. When a variable is created it occupies memory space. The data type of a variable helps the interpreter to allocate memory and decide what to be stored in the reserved memory. Therefore, variables can store integers, deci4 min readPerl | ModulesA module in Perl is a collection of related subroutines and variables that perform a set of programming tasks. Perl Modules are reusable. Various Perl modules are available on the Comprehensive Perl Archive Network (CPAN). These modules cover a wide range of categories such as network, CGI, XML proc3 min readPackages in PerlA 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 contained4 min readControl FlowPerl | 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. These6 min readPerl | 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 pro7 min readPerl | given-when Statementgiven-when statement in Perl is a substitute for long if-statements that compare a variable to several integral values. The given-when statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. given is a c4 min readPerl | goto statementThe goto statement in Perl is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function. Syntax: LABEL: Statement 1; Statement 2; . . . . . Statement n; goto LABEL; In the above syntax, the3 min readArrays & ListsPerl | ArraysIn 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",6 min readPerl | Array SlicesIn 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. Arrays can store any type of data and that data can be acce3 min readPerl | Arrays (push, pop, shift, unshift)Perl provides various inbuilt functions to add and remove the elements in an array. .string-table { font-family: arial, sans-serif; border-collapse: collapse; border: 1px solid #5fb962; width: 100%; } .string-table td, th { background-color: #c6ebd9; border: 1px solid #5fb962; text-align: left; padd3 min readPerl List and its TypesIntroduction to Lists A list is a collection of scalar values. We can access the elements of a list using indexes. Index starts with 0 (0th index refers to the first element of the list). We use parenthesis and comma operators to construct a list. In Perl, scalar variables start with a $ symbol wher4 min readHashPerl HashA hash is a set of key-value pairs. Perl stores elements of a hash such that it searches for the values based on its keys. Hash variables start with a '%' sign. Perl requires the keys of a hash to be strings, whereas the values can be any scalars. These values can either be a number, string or refer4 min readPerl | Hash OperationsPrerequisite: Perl Hashes, Perl Hash As most readers likely know, the hash stores data by using a mechanism called Hashing. In hashing, a key is used to determine a value or data. These keys must be unique and are then used as the index at which the data associated with the key is stored. This data8 min readPerl | Multidimensional HashesPrerequisite: Hashes-Basics Introduction Beyond the normal constraints of the hashes, we can also create complex structures made up of combinations of two. These are nested or complex structures and they can be used to model complex data in an easy-to-use format. Among all of the Perl's nested struc6 min readScalarsPerl | ScalarsA scalar is a variable that stores a single unit of data at a time. The data that will be stored by the scalar variable can be of the different type like string, character, floating point, a large group of strings or it can be a webpage and so on.Example : Perl # Perl program to demonstrate # scalar2 min readPerl | Comparing ScalarsPrerequisite: 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 sc6 min readPerl | scalar keywordscalar keyword in Perl is used to convert the expression to scalar context. This is a forceful evaluation of expression to scalar context even if it works well in list context. Syntax: scalar exprReturns: a scalar value Example 1: Perl #!/usr/bin/perl -w # Defining Arrays @array1 = ("Geeks2 min readStringsPerl | Quoted, Interpolated and Escaped StringsA string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers, special characters. The string can consist of a single word, a group of words or a multi-line paragraph. The String is defined by the user within a single quote (â) or double quote (â). Quoted Stri4 min readPerl | String OperatorsOperators 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 variabl4 min readPerl | 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 follow4 min readOOP ConceptsObject Oriented Programming (OOPs) in PerlObject-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 to7 min readPerl | Classes in OOPIn 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 competitivenes6 min readPerl | Objects in OOPsPerl 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 a6 min readPerl | Methods in OOPsMethods 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.5 min readPerl | Constructors and DestructorsConstructors Constructors in Perl subroutines returns an object which is an instance of the class. In Perl, the convention is to name the constructor "new". Unlike many other OOPs, Perl does not provide any special syntax for constructing an object. It uses Data structures(hashes, arrays, scalars) t4 min readPerl | Method Overriding in OOPsIn 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 signat6 min readPerl | Inheritance in OOPsInheritance 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 define7 min readPerl | Polymorphism in OOPsPolymorphism 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 object4 min readPerl | Encapsulation in OOPsEncapsulation 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. I6 min readRegular ExpressionsPerl | Regular ExpressionsRegular 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 Rege2 min readPerl | Operators in Regular ExpressionPrerequisite: Perl | Regular Expressions The Regular Expression is a string which is the combination of different characters that provides matching of the text strings. A regular expression can also be referred to as regex or regexp. The basic method for applying a regular expression is to use of bi4 min readPerl | Regex Character ClassesCharacter 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 characte3 min readPerl | Quantifiers in Regular ExpressionPerl provides several numbers of regular expression quantifiers which are used to specify how many times a given character can be repeated before matching is done. This is mainly used when the number of characters going to be matched is unknown. There are six types of Perl quantifiers which are give4 min readFile HandlingPerl | File Handling IntroductionIn Perl, file handling is the process of creating, reading, writing, updating, and deleting files. Perl provides a variety of built-in functions and modules that make it easy to work with files. Here's an introduction to file handling in Perl: File modes:When opening a file in Perl, you need to spec7 min readPerl | Opening and Reading a FileA filehandle is an internal Perl structure that associates a physical file with a name. All filehandles have read/write access, so once filehandle is attached to a file reading/writing can be done. However, the mode in which file handle is opened is to be specified while associating a filehandle. Op4 min readPerl | Writing to a FileA filehandle is a variable that is used to read and write to a file. This filehandle gets associated with the file. In order to write to the file, it is opened in write mode as shown below: open (FH, â>â, âfilename.txtâ); If the file is existing then it truncates the old content of file with the3 min readPerl | Useful File-handling functionsPerl 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. These operations can be performed by the use of various inbuilt file functions. Example: Perl #!/usr/bin/perl # Opening a2 min read Like