How to perform case-insensitive search and replace in Perl?

Question

How to perform case-insensitive search and replace in Perl?

To perform a case-insensitive search and replace in Perl, you use the substitution operator s/// along with the i modifier. This modifier makes the pattern match ignore case differences, so you can replace text regardless of capitalization. Combining it with the g flag ensures all matches in the string are replaced, not just the first one.

The substitution operator and the i modifier

The general syntax for substitution is s/pattern/replacement/flags where:

  • pattern: The regular expression pattern to find
  • replacement: The text to replace each match
  • flags: Modifiers—i for case-insensitive matching, g for global replacement

Without i, pattern matching is case-sensitive. For example, a pattern /perl/ matches "perl" but not "Perl". With i, it matches "perl", "Perl", "PERL", etc.

Example: Case-insensitive global replacement

This complete example demonstrates replacing all case variations of "perl" with "Raku":

#!/usr/bin/env perl
use strict;
use warnings;

my $text = "I love Perl, perl, and PERL!";
print "Before: $text\n";

# Perform case-insensitive, global replacement of "perl" with "Raku"
$text =~ s/perl/Raku/gi;

print "After: $text\n";

When you run this code, you get:

Before: I love Perl, perl, and PERL!
After: I love Raku, Raku, and Raku!

Key points explained

  • =~ operator applies the substitution to the variable $text
  • The pattern perl is matched ignoring case due to i
  • The g flag ensures all matches in the string are replaced
  • The replacement string "Raku" is literal and inserted as-is

Common pitfalls and tips

  • For replacing all occurrences, don't forget the g flag
  • The i modifier affects pattern matching only, not the replacement string's case
  • Escape special regex characters in your pattern if needed, e.g., \. for a literal dot
  • If you want to run code during replacement, use the e flag (e.g., s/(\d+)/$1 * 2/ge)

The s///i substitution with optional g is Perl's classic way for case-insensitive text replacement, leveraging Perl's powerful regex engine.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 15ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Before: I love Perl, perl, and PERL!
After: I love Raku, Raku, and Raku!
STDERR
(empty)

Was this helpful?

Related Questions