Check whether a string contains a substring


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

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

This question is tagged with string perl string-matching

~ Asked on 2011-09-02 12:17:58

The Best Answer is


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.

~ Answered on 2011-09-02 12:21:00


Another possibility is to use regular expressions which is what Perl is famous for:

if ($mystring =~ /s1\.domain\.com/) {
   print qq("$mystring" contains ""\n);

The backslashes are needed because a . can match any character. You can get around this by using the \Q and \E operators.

my $substring = "";
    if ($mystring =~ /\Q$substring\E/) {
   print qq("$mystring" contains "$substring"\n);

Or, you can do as eugene y stated and use the index function. Just a word of warning: Index returns a -1 when it can't find a match instead of an undef or 0.

Thus, this is an error:

my $substring = "";
if (not index($mystring, $substr)) {
    print qq("$mystring" doesn't contains "$substring"\n";

This will be wrong if is at the beginning of your string. I've personally been burned on this more than once.

~ Answered on 2011-09-02 13:04:08

Most Viewed Questions: