Lesson 40 of 55
9 mins readPython Search & Replace: Substitution Operator (s///)
In Plain English
The substitution operator `s/pattern/replacement/flags` searches for a pattern in a scalar and replaces it. Flags include `/g` (global), `/i` (case-insensitive), and `/r` (non-destructive return).
Deep Dive: How It Works
Syntax: `$str =~ s/search/replace/flags;`.
Global (/g): Replaces all occurrences instead of only the first.
Case-Insensitive (/i): Ignores upper/lowercase differences.
Non-Destructive (/r): Returns the modified copy leaving the original scalar unchanged.
Executable (/e): Evaluates the replacement string as Perl code before replacing.
Core Rules to Remember

s/// Operator: Directly transforms strings matching target patterns.

/r for Non-Destructive Copy: `my $clean = $raw =~ s/\s+//gr;` keeps `$raw` intact.
Live Interactive Example
Hit Run Code to see it liveGlobal Substitution and Normalization
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Output Console
Click "Run Code" to view the rendered output.
How it works: s/brown/red/ mutated $text, while /gr returned the masked version non-destructively.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Sanitize Phone Number with s///g
Set `my $phone = "(555) 123-4567";`
Strip all non-digits using `$phone =~ s/\D//g;`
Print `"Clean digits: $phone\n"`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.