Search⌘ K
AI Features

Solution Review: Check Substring

Explore how to create a Perl subroutine that checks if one string contains another substring. Learn to use Perl's index function to find occurrences and return meaningful results for substring detection.

We'll cover the following...

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

Perl
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.