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.
This question is related to
string
perl
string-matching
For case-insensitive string search, use index
(or rindex
) in combination with fc
. This example expands on the answer by Eugene Yarmash:
use feature qw( fc );
my $str = "Abc";
my $substr = "aB";
print "found" if index( fc $str, fc $substr ) != -1;
# Prints: found
print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints: found
$str = "Abc";
$substr = "bA";
print "found" if index( fc $str, fc $substr ) != -1;
# Prints nothing
print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints nothing
Both index
and rindex
return -1
if the substring is not found.
And fc
returns a casefolded version of its string argument, and should be used here instead of the (more familiar) uc
or lc
. Remember to enable this function, for example with use feature qw( fc );
.
if ($string =~ m/something/) {
# Do work
}
Where something
is a regular expression.
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";
}
Source: Stackoverflow.com