Perl - If string contains text?

Hellos picture Hellos · Aug 10, 2011 · Viewed 228.3k times · Source

I want to use curl to view the source of a page and if that source contains a word that matches the string then it will execute a print. How would I do a if $string contains?

In VB it would be like.

dim string1 as string = "1"
If string1.contains("1") Then
Code here...
End If

Something similar to that but in Perl.

Answer

Eugene Yarmash picture Eugene Yarmash · Aug 10, 2011

If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

if (index($string, $substring) != -1) {
   print "'$string' contains '$substring'\n";
}

To search a string for a pattern match, use the match operator m//:

if ($string =~ m/pattern/) {
    print "'$string' matches the pattern\n";       
}