Thursday, January 13, 2011

Simple String Comparisons

The most basic string comparison is
$string =~ m/sought_text/;
The above returns true if string $string contains substring "sought_text", false otherwise. If you want only those strings where the sought text appears at the very beginning, you could write the following:
$string =~ m/^sought_text/;
Similarly, the $ operator indicates "end of string". If you wanted to find out if the sought text was the very last text in the string, you could write this:
$string =~ m/sought_text$/;
Now, if you want the comparison to be true only if $string contains the sought text and nothing but the sought text, simply do this:
$string =~ m/^sought_text$/;
Now what if you want the comparison to be case insensitive? All you do is add the letter i after the ending delimiter:
$string =~ m/^sought_text$/i;

No comments: