The Substitution Operator in Perl


The substitution operator s/// in Perl is really just an extension of the match operator that allows you to replace the text matched with some new text. The basic form of the operator is −

s/PATTERN/REPLACEMENT/;

The PATTERN is the regular expression for the text that we are looking for. The REPLACEMENT is a specification for the text or regular expression that we want to use to replace the found text with. For example, we can replace all occurrences of dog with cat using the following regular expression −

Example

 Live Demo

#/user/bin/perl
$string = "The cat sat on the mat";
$string =~ s/cat/dog/;
print "$string\n";

When the above program is executed, it produces the following result −

The dog sat on the mat

Substitution Operator Modifiers

Here is the list of all the modifiers used with substitution operator.

Sr.NoModifier & Description
1i
Makes the match case insensitive.
2m
Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.
3o
Evaluates the expression only once.
4s
Allows use of . to match a newline character.
5x
Allows you to use white space in the expression for clarity.
6g
Replaces all occurrences of the found expression with the replacement text.
7e
Evaluates the replacement as if it were a Perl statement, and uses its return value as the replacement text.

Updated on: 29-Nov-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements