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.
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.
Another possibility is to use regular expressions which is what Perl is famous for:
The backslashes are needed because a
.
can match any character. You can get around this by using the\Q
and\E
operators.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 anundef
or0
.Thus, this is an error:
This will be wrong if
s1.domain.com
is at the beginning of your string. I've personally been burned on this more than once.Case Insensitive Substring Example
This is an extension of Eugene's answer, which converts the strings to lower case before checking for the substring:
To find out if a string contains substring you can use the
index
function:It will return the position of the first occurrence of
$substr
in$str
, or -1 if the substring is not found.