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 −


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 −


 Live Demo

$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
Makes the match case insensitive.
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.
Evaluates the expression only once.
Allows use of . to match a newline character.
Allows you to use white space in the expression for clarity.
Replaces all occurrences of the found expression with the replacement text.
Evaluates the replacement as if it were a Perl statement, and uses its return value as the replacement text.