← Back to Perl Course | Chapter 4: Regular Expressions | Lesson 6 of 7

Substitution

s/pattern/replacement/ finds text and replaces it.

In this page:

  1. Substitution

Substitution

The s/// operator changes the string it is bound to and returns the number of replacements made. Add /g to replace every match, /i to ignore case, and /r to return the new string instead of changing the original. With /e the replacement part is evaluated as Perl code, so you can calculate the new text.

Note: Use /r to transform a copy in one expression, such as print $text =~ s/a/b/gr.

Example: Substitution

perl
use strict;
use warnings;

my $text = "I like cats. Cats are great; my cat is grey.";
(my $copy = $text) =~ s/cat/dog/;
print "first only: $copy\n";
my $n = ($copy = $text) =~ s/cat/dog/gi;
print "all, ignoring case ($n): $copy\n";
print "with /r: ", $text =~ s/great/wonderful/r, "\n";
print "original kept: $text\n";
my $prices = "apple 3, pear 5";
$prices =~ s/(\d+)/$1 * 2/ge;
print "doubled: $prices\n";
my $swap = "Smith, John";
$swap =~ s/(\w+), (\w+)/$2 $1/;
print "swapped: $swap\n";

# Output:
# first only: I like dogs. Cats are great; my cat is grey.
# all, ignoring case (3): I like dogs. dogs are great; my dog is grey.
# with /r: I like cats. Cats are wonderful; my cat is grey.
# original kept: I like cats. Cats are great; my cat is grey.
# doubled: apple 6, pear 10
# swapped: John Smith
Common Mistakes
  1. Forgetting /g and replacing only the first match
  2. Trying to use s/// on a constant string
  3. Forgetting that s/// modifies the variable unless /r is used
Chapter Summary
  • s/old/new/ replaces the first match
  • /g replaces all matches
  • /r returns a modified copy
  • /e evaluates the replacement as code
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.