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 findreplacement: The text to replace each matchflags: Modifiers—ifor case-insensitive matching,gfor 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
perlis matched ignoring case due toi - The
gflag 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
gflag - The
imodifier 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
eflag (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
Before: I love Perl, perl, and PERL!
After: I love Raku, Raku, and Raku!
(empty)