regex beginner
How to perform a global substitution in Perl?
Question
How to perform a global substitution in Perl?
In Perl, to perform a global substitution, you use the substitution operator s/// with the g modifier. This replaces all occurrences of a pattern inside a string, instead of just the first one.
Basic Syntax
The general form is:
s/pattern/replacement/g
Where:
patternis a regular expression to match within the string,replacementis the new text to substitute,gmeans "global" (replace all matches, not just the first).
Working Example: Replace All Instances of "dog" with "cat"
The following Perl script demonstrates a simple global substitution and prints the result:
use strict;
use warnings;
my $text = "dog dog dog";
print "Original: $text\n";
# Global substitution replaces every "dog" with "cat"
$text =~ s/dog/cat/g;
print "Modified: $text\n";
Running this will output:
Original: dog dog dog
Modified: cat cat cat
Perl-Specific Concepts
$is the scalar sigil, indicating a scalar variable holding a string.=~applies the regex operation on the string variable.s///is the substitution operator itself.gmeans global replacement.- Perl supports alternate delimiters:
s!dog!cat!gors{dog}{cat}gto avoid escaping slashes. - TMTOWTDI ("There’s more than one way to do it") applies here for regex variations.
Common Pitfalls
- Forgetting the
gmodifier replaces only the first matching substring. - Using invalid regex modifiers causes compilation errors (e.g.,
/fis invalid). - Patterns or replacements containing
/benefit from alternate delimiters to reduce escaping. - Remember, the substitution operator returns true or false based on whether it made a substitution—not the new string.
Summary
Use the idiomatic syntax:
$string =~ s/pattern/replacement/g;
This is the fundamental way to do global search-and-replace in Perl strings reliably and efficiently.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 9ms
Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)STDERR
(empty)Was this helpful?
Related Questions
- How to validate email addresses using Perl regex?
- How to split a string by regex pattern in Perl?
- How to use greedy vs non-greedy quantifiers in Perl regex?
- How to match start and end of string with ^ and $ in Perl?
- How to use alternation | in Perl regex?
- How to use the qr// operator to compile regex in Perl?