简体   繁体   English

为什么比较运算符==不适用于perl中的字符串?

[英]Why comparison operator == does not work for strings in perl?

I'm new to Perl. 我是Perl的新手。 I want to understand why does == operator is treating both these strings alike? 我想了解为什么==运算符会像对待这两个字符串一样? It works ok if I use eq instead if ==. 如果我使用eq代替if ==,它可以正常工作。 If name is kuldeep or rahul, it prints 'Right name'. 如果名称是kuldeep或rahul,则会显示“正确的名称”。

my $name="kuldeep";

if ($name == "rahul")
{
  print 'Right name!',"\n";
}
else
{
  print 'Wrong name!','\n';
}

You are mistaken. 你误会了。 The numerical equality comparison operator works perfectly fine with strings! 数值相等比较运算符与字符串完美配合!

$ perl -e'CORE::say "123" == "123.0" ? "same" : "different"'
same

$ perl -e'CORE::say "123" == "123.1" ? "same" : "different"'
different

In your example, you are asking Perl to compare the numerical value of the string kuldeep (zero with a warning) with the numerical value of the string rahul (zero with a warning), and they are indeed equal. 在您的示例中,您要求Perl将字符串kuldeep (带有警告的零)和rahul (带有警告的零)的数值进行比较,它们的确相等。

ALWAYS USE use strict; use warnings; 始终use strict; use warnings; use strict; use warnings; !!! !!!

And use eq to compare strings. 并使用eq比较字符串。

Interpreter realizes (from the == operator) that it's doing a numeric comparison. 解释器(通过==运算符)意识到它正在进行数字比较。 The value of $name is converted to a numeric, which gets you a 0. "rahul" is converted to a numeric, which is a 0. 0 == 0, so that's true, and thus "Right name" is chosen. $ name的值将转换为数字,从而得到0。“ rahul”将转换为数字,即0。0== 0,这是正确的,因此选择了“ Right name”。

If I compare it against my name, works the same way. 如果我将其与我的名字进行比较,则其工作方式相同。

However, if there really is a string with a number in it, like you made either string "12345" (specifically with the quotes), Perl will assume you knew what you were doing by requesting the == operator, and will dutifully auto-convert ("cast" in programmer-speak) that to numeric 12345. Then your comparison will fail. 但是,如果确实有一个带数字的字符串,例如您将字符串设为“ 12345”(特别是带引号),Perl就会通过请求==运算符来假定您知道自己在做什么,并且会忠实地自动执行-将其转换(用程序员来说是“ cast”)转换为数字12345。然后您的比较将失败。

TL/DR: use 'eq' for string comparison! TL / DR:使用“ eq”进行字符串比较! :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM