Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String compare in Perl with "eq" vs "==" [duplicate]

Tags:

string

perl

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?

like image 538
hari Avatar asked Dec 26 '12 21:12

hari


People also ask

What is the difference between == and EQ in Perl?

== is used when comparing numeric values. eq is used in comparing string values.

Can we use == for string comparison?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do I check if two strings are equal in Perl?

'eq' operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise equal to the string to its right.

What is == in Perl?

"== does a numeric comparison: it converts both arguments to a number and then compares them." "eq does a string comparison: the two arguments must match lexically (case-sensitive)"


1 Answers

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.

like image 139
PSIAlt Avatar answered Sep 28 '22 03:09

PSIAlt