在Perl中将字符串与"eq"进行比较vs"==" [英] String compare in Perl with "eq" vs "=="
问题描述
我(一个完整的Perl新手)正在if
语句中进行字符串比较:
I am (a complete Perl newbie) doing string compare in an if
statement:
如果我执行以下操作:
if ($str1 == "taste" && $str2 == "waste") { }
我看到了正确的结果(即,如果条件匹配,它将评估"then"块).但是我看到了这些警告:
I see the correct result (i.e. if the condition matches, it evaluates the "then" block). But I see these warnings:
在行号x的数字eq(==)中,参数"taste"不是数字.
在行号x的数字eq(==)中,参数"waste"不是数字.
Argument "taste" isn't numeric in numeric eq (==) at line number x.
Argument "waste" isn't numeric in numeric eq (==) at line number x.
但如果我这样做:
if ($str1 eq "taste" && $str2 eq "waste") { }
即使满足if条件,也不会评估"then"块.
Even if the if condition is satisfied, it doesn't evaluate the "then" block.
在这里,$str1
是taste
,$str2
是waste
.
我该如何解决?
推荐答案
首先, eq 用于比较字符串; == 用于比较数字.
First, eq is for comparing strings; == is for comparing numbers.
即使满足"if"条件,也不会评估"then"块.
Even if the "if" condition is satisfied, it doesn't evaluate the "then" block.
我认为您的问题是您的变量不包含您认为的变量.我认为您的$str1
或$str2
包含"taste \ n"之类的内容.通过在 if :print "str1='$str1'\n";
之前打印进行检查.
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";
.
可以使用chomp($str1);
函数删除尾随的换行符.
The trailing newline can be removed with the chomp($str1);
function.
这篇关于在Perl中将字符串与"eq"进行比较vs"=="的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!