The obvious answer is to use the /i modifier at the end of the regular expression to cause the regexp to behave in a "case insensitive" way. You can do this as follows:
my $string = "This needs to match!";
if ( $string =~ /mAtCh/i ) {
print $string, " matched.\n";
}
In many situations this is the right way to do it.
But as Friedl points out in Mastering Regular Expressions (the Owls book), the /i modifier can be extremely costly if you're scanning through a lot of text. See the section called, "Perl Efficiency Issues" for details.
The net result can be minimal on just a line or two of text, but as Friedl illustrates, in searching case insensitively for while m/./gi in a 1MB file (read as a single line), the match with /i took a day and a half to complete, whereas without /i, the match completed in 12 seconds.
Again, paraphrasing Friedl...
This was obviously a worst-case scenario. But even in the comparison of m/\bwhile\b/gi against m/\b[Ww][Hh][Ii][Ll][Ee]\b/g, the non-/i version was 50 times faster (though a lot uglier and still pretty inefficient because it prevents Perl's fixed string check and renders study useless).
My suggestion is that if you have to match on a small string of text in a case-insensitive way, use /i. But if the string is likely to be quite large, and efficiency matters to you, find an alternative to the /i modifier.
Here is one possible alternative:
my $string = "Here is some TEXT.";
{
my $teststr = lc $string;
if ( $teststr =~ m/text/ ) { print "$string matched.\n"; }
}
Admittedly this method makes a copy of $string. You could avoid that if you didn't mind converting $string itself to lc or uc. But the point is that the /i operator actually can cause multiple copies of the same string to be made and later discarded. In a worst case scenario, a 1MB string that Friedl used had over 600MB of data being copied around by the regexp engine as it tried to match while applying the /i modifier. In a real-world case, the penalty of using /i is much smaller. But just as we take notice any time $&, $`, and $' are used, take notice whenever you use /i.
Thanks to Friedl's Mastering Regular Expressions book, we don't all have to test the /i switch on huge files to verify its efficiency; we can take his word for it. He's done all the research on the subject we need.
/i is a tool, and is there to be used, just as $&, $`, and $'. Clearly its use is not deprecated. But it is a tool that comes at perhaps a higher efficiency cost than unsuspecting users might imagine. Understand the ramifications, and then plan your code accordingly.
Dave
"If I had my life to do over again, I'd be a plumber." -- Albert Einstein |