Check whether a string contains a substring

Belgin Fish picture Belgin Fish · Sep 2, 2011 · Viewed 331.9k times · Source

How can I check whether a given string contains a certain substring, using Perl?

More specifically, I want to see whether s1.domain.com is present in the given string variable.

Answer

Eugene Yarmash picture Eugene Yarmash · Sep 2, 2011

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.