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:

  • pattern is a regular expression to match within the string,
  • replacement is the new text to substitute,
  • g means "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.
  • g means global replacement.
  • Perl supports alternate delimiters: s!dog!cat!g or s{dog}{cat}g to avoid escaping slashes.
  • TMTOWTDI ("There’s more than one way to do it") applies here for regex variations.

Common Pitfalls

  • Forgetting the g modifier replaces only the first matching substring.
  • Using invalid regex modifiers causes compilation errors (e.g., /f is 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