Perl 中的字符串与“eq"比较与“==" [英] String compare in Perl with "eq" vs "=="

查看:30
本文介绍了Perl 中的字符串与“eq"比较与“=="的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我(一个完整的 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.

这里,$str1taste$str2waste.

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

我应该如何解决这个问题?

How should I fix this?

推荐答案

首先,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 "之类的东西.通过在 if 之前打印来检查它们:print "str1='$str1' ";.

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 " or so. Check them by printing before your if: print "str1='$str1' ";.

可以使用 chomp($str1); 函数删除尾随的换行符.

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

这篇关于Perl 中的字符串与“eq"比较与“=="的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆