Jayesh Ranjan Majhi
Jayesh Ranjan Majhi

Reputation: 39

How to Compare two string stored in variables in Perl?

I want to check if $test1 is present in $test2 and $test3.

I tried with the following code but I am not getting the correct output.

my $test1 = "cat";
my $test2 = "My name is cat";
my $test3 = "My name is apple";

if($test2  eq /$test1/){
    print "yes2\n";
}

if($test3 eq /$test1/){
   print "yes3\n";
}

Upvotes: 1

Views: 2309

Answers (3)

user7818749
user7818749

Reputation:

Here is another method, not using if directly.

$result = ($test2  =~ /\b$test1\b/) ? "Matched" : "No Match";
print "$result\n";

Upvotes: 1

Gaétan RYCKEBOER
Gaétan RYCKEBOER

Reputation: 304

The simplest way to check a string contained in another one is via a regular expression :

print "Found." if ( $test2 ~= /$test1/);

in your case, you would even be more concise :

foreach $str in ( $test1, $test2 ) {
   print "Found $test1 in $str." if ( $str ~= /$test1/);
}

or even, using default assignemnt :

foreach ( $test1, $test2 ) {
   print "Found $test1 in $str." if ( /$test1/ );
}

The test is checking against $_, which is automatically assigned by the foreach clause.

Upvotes: 0

Toto
Toto

Reputation: 91385

To match a regex use =~ operator:

if($test2  =~ /$test1/){
    print "yes2\n";
}

if($test3 =~ /$test1/){
   print "yes3\n";
}

You could use word boundaries to match exactly, to avoid matching caterpillar:

if($test2  =~ /\b$test1\b/){
    print "yes2\n";
}

if($test3 =~ /\b$test1\b/){
   print "yes3\n";
}

Upvotes: 2

Related Questions