How to test if a string contains another string in Perl?

thomaszhwang
thomaszhwang used Ask the Experts™
on
Both strings are in variables which come from a database which collects the string from end users, so those strings could contain anything like . ? and etc.

Thanks.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
If string $a contains $b, you can test it like

if($a =~ /$b/)

Open in new window

You can also try using the index() perl function:

#!/usr/bin/perl

my $stringFromDatabase = "thisissomestringfromthedatabase";
my $stringFromTheUser = "database";

$result = index($stringFromDatabase, $stringFromTheUser);
if ( $result == -1 ) {
      print "$stringFromTheUser was not found.\n";
} else {
      print "$stringFromTheUser was found. The first occurrence starts at character $result .\n";
}

Author

Commented:
Thanks.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial