String compare in Perl with "eq" vs "=="

StringPerl

String Problem Overview


I am (a complete Perl newbie) doing string compare in an if statement:

If I do following:

if ($str1 == "taste" && $str2 == "waste") { }

I see the correct result (i.e. if the condition matches, it evaluates the "then" block). But I see these warnings:

> Argument "taste" isn't numeric in numeric eq (==) at line number x.
> Argument "waste" isn't numeric in numeric eq (==) at line number x.

But if I do:

if ($str1 eq "taste" && $str2 eq "waste") { }

Even if the if condition is satisfied, it doesn't evaluate the "then" block.

Here, $str1 is taste and $str2 is waste.

How should I fix this?

String Solutions


Solution 1 - String

First, eq is for comparing strings; == is for comparing numbers.

> Even if the "if" condition is satisfied, it doesn't evaluate the "then" block.

I think your problem is that your variables don't contain what you think they do. I think your $str1 or $str2 contains something like "taste\n" or so. Check them by printing before your if: print "str1='$str1'\n";.

The trailing newline can be removed with the chomp($str1); function.

Solution 2 - String

== does a numeric comparison: it converts both arguments to a number and then compares them. As long as $str1 and $str2 both evaluate to 0 as numbers, the condition will be satisfied.

eq does a string comparison: the two arguments must match lexically (case-sensitive) for the condition to be satisfied.

"foo" == "bar";   # True, both strings evaluate to 0.
"foo" eq "bar";   # False, the strings are not equivalent.
"Foo" eq "foo";   # False, the F characters are different cases.
"foo" eq "foo";   # True, both strings match exactly.

Solution 3 - String

Did you try to chomp the $str1 and $str2?

I found a similar issue with using (another) $str1 eq 'Y' and it only went away when I first did:

chomp($str1);
if ($str1 eq 'Y') {
....
}

works after that.

Hope that helps.

Solution 4 - String

Maybe the condition you are using is incorrect:

$str1 == "taste" && $str2 == "waste"

The program will enter into THEN part only when both of the stated conditions are true.

You can try with $str1 == "taste" || $str2 == "waste". This will execute the THEN part if anyone of the above conditions are true.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhariView Question on Stackoverflow
Solution 1 - StringGalimov AlbertView Answer on Stackoverflow
Solution 2 - StringcdhowieView Answer on Stackoverflow
Solution 3 - Stringuser4185253View Answer on Stackoverflow
Solution 4 - Stringuser1931990View Answer on Stackoverflow