Perl | Operators in Regular Expression Last Updated : 22 Feb, 2023 Comments Improve Suggest changes Like Article Like Report Prerequisite: 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 binding operators =~ (Regex Operator) and !~ (Negated Regex Operator). There are three types of regular expression operators in Perl: Match Regular ExpressionSubstitute (Search and replace) Regular ExpressionGlobal Character Transliteration Regular Expression 1) Pattern Matching or Match Regular Expression: The match operator "m//" is used to match a string or a statement against a regular expression. The forward slash used in the operator ( m// ) acts as the delimiter and this delimiter can also be like m{}, m(), and m><, etc. The expression is written in between two forward slashes used in the operator. Syntax: m/PATTERN/ Here, PATTERN is the Regular Expression to be searched in the string Let's see some examples illustrating the pattern matching: In the below examples, a string and regular expression is matched, on success it returns "match found" otherwise "match not found". Example 1: perl #!/user/bin/perl # Initializing a string $a = "GeeksforGeeks"; # matching the string and # a regular expression and returns # match found or not if ($a =~ m/for/) { print "Match Found\n"; } else { print "Match Not Found\n"; } Output: Match Found Example 2: perl #!/user/bin/perl # Initialising an string $a = "GeeksforGeeks"; # matching the string and # a regular expression and returns # match found or not if ($a =~ m:abc:) { print "Match Found\n"; } else { print "Match Not Found\n"; } Output: Match Not Found Here, in the above code a different delimiter ':' is used instead of '/', this shows that it is not necessary to use '/' as a delimiter. 2) Substitute (Search and replace) Regular Expression: The substitute operator "s///" is used to search a specific word and then replace it with a given regular expression. The forward slash used in the operator ( s/// ) acts as the delimiter. Syntax: s/PATTERN/REPLACEMENT/; Here PATTERN is the regular expression which is to be replaced with REPLACEMENT regular expression. Let's see some examples illustrating the substitute regular expression: In the below examples, a PATTERN word is searched first then it is replaced with the REPLACEMENT word. Example-1: perl #/user/bin/perl # Initialising a string $string = "GeeksforGeeks is a computer science portal."; # Calling the substitute regular expression $string =~ s/GeeksforGeeks/gfg/; $string =~ s/computer science/cs/; # Printing the substituted string print "$string\n"; Output: gfg is a cs portal. Example-2: perl #/user/bin/perl # Initialising a string $string = "10001"; # Calling the substitution regular expression $string =~ s/000/999/; # Printing the substituted string print "$string\n"; Output: 19991 3) Global Character Transliteration regular expression: The translation or transliteration operator "tr///" or "y///" is used to replace all the occurrences of a character with a given single character. The forward slash used in the operator ( tr/// and y/// ) acts as the delimiter. Syntax: tr/SEARCHLIST/REPLACEMENTLIST/ y/SEARCHLIST/REPLACEMENTLIST/ Here SEARCHLIST is the character whose all the occurrences are going to be replaced with the character in REPLACEMENTLIST. Let's see some examples illustrating the translation regular expression: In the below examples, all occurrences of "G" are replaced with "g" with two different operators "tr///" and "y///". Example 1: perl #/user/bin/perl # Initialising a string $string = 'GeeksforGeeks'; # Calling the tr/// operator $string =~ tr/G/g/; # Printing the replaced string print "$string\n"; Output: geeksforgeeks Example 2: perl #/user/bin/perl # Initialising a string $string = 'GeeksforGeeks'; # Calling the y/// operator $string =~ y/G/g/; # Printing the replaced string print "$string\n"; Output: geeksforgeeks Comment More infoAdvertise with us Next Article Perl | Regex Character Classes K Kanchan_Ray Follow Improve Article Tags : Perl Perl-regex 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