Perl - Attributes in Object Oriented Programming Last Updated : 15 Jul, 2025 Comments Improve Suggest changes Like Article Like Report In Perl, Object Oriented concept is very much based on references and Arrays/Hashes. The few main terms of object-oriented programming with respect to Perl programming are object, class, and method. In Perl, an object is like a reference to a data type that knows about the class it belongs to. The object is stored as a reference present in the scalar variable. And since scalar only contains a reference to the object, it can even hold different objects present in separate classes.In Perl, a package containing corresponding methods which are required to create and manipulate objects is known as a class.In Perl, the method is a subroutine that is defined within the package. A package name or an object reference is the first argument to the method depending on whether the method affects the current class or object.Attributes Attributes can be defined by each class. When we represent them as objects, we assign values to those attributes. For eg, even every ‘file’ object has a path. Attributes are also known as properties. Attributes are typically defined as read-only or read-write. Read-only attributes can be set only when the object is created, while read-write attributes can be altered at any time. The value of an attribute can itself be another object. And it's not necessary for every class to have attributes and methods. Perl has no special syntax for attributes. In the back, attributes are often stored as keys in the object's underlying hash. Perl sub new{ my ($class, $args) = @_; my $self = bless { serial => $args->{serial}, name => $args->{name}, price => $args->{price} }, $class; } Whenever we call the new() method, Perl automatically passes the class name as the first argument to the special array @_.When we create an object, we actually create a reference that knows about the class it belongs to. Bless (which is a built-in function) is used to bless the reference to the class and then return an instance of the class. In the above example, we have passed a hash reference to the bless() function. But one can pass any kind of reference to the bless function e.g., array reference, which makes it much easier to work with a hash reference. Creating default attribute values Now we can know how to apply attributes. But what will happen if we don’t pass all the arguments in our Perl program? In this case, the attributes will be initialized as ‘null’ by the object. Hence there is a way to avoid that by setting default values that are overridden if the argument is present when the object is constructed. Logical or operator || can be used to achieve this effect. Perl sub new{ sub new{ my ($class, $args) = @_; my $self = { name => $args->{name} || ‘iPhone XR’, price => $args->{price} || ‘52K’, }, Return bless $self, $class; } 1; Accessing attributes The best way to accessing attributes is via accessor methods. These are methods that help us in Perl to get or set the value of each attribute. The two types of accessor are: Getter: It gets the attribute's value.Setter(also known as Mutator): It sets the attributes value. Perl package Person; use strict; use warnings; sub new { my ($class, %args) = @_; my $self = \%args; bless $self, $class; return $self; } sub name { my ($self, $value) = @_; if (@_ == 2) { $self->{name} = $value; } return $self->{name}; } 1; # Assigning the object 'Person' # to the $teacher variable. my $teacher = Person->new; # Setting the attribute 'name' # to the variable '$teacher' $teacher->name('Foo'); printf $teacher->name; Output:Foo We are calling the constructor here Person->new, which returns an object we assign to $teacher and then we are calling the accessor $teacher->name('Foo') using it as a setter by providing it a value and then using the same accessor as a getter $teacher->name (without passing a value) making it fetch the current value of the attribute while using the same method called ‘name’. When we call the $teacher->name('Foo'), Perl will notice that $teacher is a blessed reference to a hash and it was blessed into the Person (name-space). If there wasn't a blessed reference, it wouldn’t have known what to do with the arrow and the "name" after that and it would’ve throw an exception: (Can't call method .. on unblessed reference) Well since it is blessed into the Person name-space, Perl will start to look for the "name" function in the Person name-space and once that function is found, Perl will call that function with the parameters which we’ve passed onto it, but it will also take the variable we had on the left-hand side of the arrow and pass it as the first argument. ($teacher in our case) .In our example this "name" function is once called as a "setter" when we pass a value to it, and once as "getter" when we don't pass any value through it. Because Perl passes the object as the first parameter this means that when it is called a "setter" we are actually going to get 2 parameters and when it is called a "getter" we are going to get one parameter.The first statement in the "name" subroutine assigns the parameters to local variables. In the second statement now, Perl checks whether the function should act as a getter or as a setter? Perl checks the number of parameters. If it gets two parameters then this is a setter. In this case, it takes the content of $self.If we use the 'name' function as a 'getter', then we don't pass any value to it, which means $value will be undefined, but more importantly @_ will only have one element. This it will skip the assignment and the only thing it’ll do is to return the value of the 'name' key from the hash reference. Conclusion: This shows that the attributes of an object in Perl are just key/value pairs in a hash reference.In the above example, we can see that the setter/getter is just a plain Perl function.Therefore it also implements that the attributes of an object are simple entries in the HASH reference representing the object. The key in the hash is the name of the attribute and the respective value in the HASH is the value of the attribute. Comment More infoAdvertise with us Next Article Introduction to Perl V vishalraina Follow Improve Article Tags : Perl 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