Solution Review: Check Substring

Let's go over the solution review of the challenge given in the previous lesson.

We'll cover the following

Let’s look at the solution first before jumping into the explanation:

Press + to interact
sub stringCheck{
$str1 = @_[0];
$str2 = @_[1];
if(index($str1, $str2) >= 0) {
return 1;
}
else {
return -1;
}
}
$Str = "The quick brown fox jumps over the lazy dog.";
print stringCheck($Str, "over")

Explanation

The stringCheck subroutine takes two string parameters. Both of them are passed to the index subroutine. It checks the occurrence of the second string in the first one and its index is returned. It returns -1 if the second string does not exist in the first string. The stringCheck subroutine returns 1 if the first string contains the second string as its substring. Otherwise, it returns -1.