The Wayback Machine - https://web.archive.org/web/20240930192651/https://www.geeksforgeeks.org/perl-operators-in-regular-expression/
Open In App

Perl | Operators in Regular Expression

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

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:

  1. Match Regular Expression
  2. Substitute (Search and replace) Regular Expression
  3. Global 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


Previous Article
Next Article

Similar Reads

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 | Quantifiers in Regular Expression
Perl 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 given below: * = This says the component must be prese
4 min read
Perl | pos() function in Regular Expression
pos() function in Perl is used to return the position of the last match using the 'm' modifier in Regex. pos function can be used with the character classes in Regex to return a list of all the required substring positions in the given string. Global operator 'g' can also be used along with the 'm' modifier to search for the substring within the wh
3 min read
Perl | 'e' modifier in Regular Expression
In Perl, the regular expression allows performing various operations on a given string with the use of suitable operators. These operators can perform operations like modification of string, substitution of other substrings, etc. Substitution of a substring in the given string is done with the use of 's'(substitution) operator, which takes two oper
3 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 | 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 | 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 - Use of Capturing in Regular Expressions
A regular expression or a regex is a string of characters that define the pattern that we are viewing. It is a special string describing a search pattern present inside a given text. Perl allows us to group portions of these patterns together into a subpattern and also remembers the string matched by those subpatterns. This behaviour is known as Ca
3 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 | 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 | 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 | File Test Operators
File Test Operators in Perl are the logical operators which return True or False values. There are many operators in Perl that you can use to test various different aspects of a file. For example, to check for the existence of a file -e operator is used. Or, it can be checked if a file can be written to before performing the append operation. This
3 min read
Perl | Useful String Operators
A 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 (“). Operators are the foundation of any programming language, so
3 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 | 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 | 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 | 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 | 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 | 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
Article Tags :