IF 语句出现意外结果:“string” <= 72 是真的吗?
在下面的代码中,当我在输入处输入一些非数字字母(即 $temp
)时,它会响应“太冷了!”而不是“无效”。我缺少什么?
#!/usr/bin/perl
print "What is the temperature outside? ";
$temp=<>;
if ($temp > 72) {
print "Too hot!\n"; }
elsif ($temp <= 72) {
print "Too cold!\n"; }
else {
print "Temperature $temp is invalid.\n"; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是因为如果不能转换为数字,它将被视为 0。您应该先检查响应是否只有数字,或以任何其他方式限制输入,以便只能输入有效的数字。大致内容如下:(
如果
$temp
包含任何非数字字符,则打印无效。请注意,这可能会使“+”和“-”无效,但您明白了)。This is because it will be treated as 0 if it cannot be converted into a number. You should check before if the response has only numbers, or restrict the input in any other way so that only a valid number can be entered. Something along the lines:
(prints invalid if
$temp
contains any non-digit character. Note that this may invalidate "+" and "-", but you get the idea).数字比较运算符期望它们的参数是数字。如果您尝试使用数字比较来比较像
'foo'
这样的字符串,它将自动转换为数字0
,该数字小于72.
如果您打开了警告,您就会被告知发生了什么事。
这就是为什么你应该始终以以下方式开始你的程序
The numerical comparison operators expect their arguments to be numbers. If you try to compare a string like
'foo'
using a numerical comparison, it will be converted silently to the number0
, which is less than72
.If you had warnings turned on, you would have been told what was going on.
This is why you should always begin your programs with
将无效的数字字符串转换为数字会导致
0
,因此您可以使用如下所示的内容来查看输入是否确实有效。解释:如果输入字符串被转换为 0(零),尽管字符串本身不等于“0”(零),则输入不是数字,因此;无效的。
您还可以使用正则表达式检查输入是否仅由
[0-9.]
组成,这将确保它是有效的数字(另请记住,数字不以 0 开头(零),然后是后面的数字,除非您使用八进制书写注意:请记住在进行上述检查之前删除输入字符串中的空格。
Casting an invalid numerical string to a number results in
0
, therefor you could use something as the below to see if the input was indeed valid or not.Explanation: If the input string was casted into 0 (zero) though the string itself isn't equal to '0' (zero) the input is not numeric, hence; invalid.
You could also check to see if the input only consists of
[0-9.]
by using a regular expression, that would ensure that it's a valid number (also remember that numbers do not start with 0 (zero) and then have digits that follow, unless you are writing in octal.Note: Remember to trim the input string from white spaces before the above check.
正是由于这个原因(以及许多其他原因),如果启用“使用警告”,情况会好得多:
For precisely this reason (and many others), you're MUCH better off if you enable "use warnings":
删除尾随换行符后尝试一下,这可能是导致 Perl 将其视为字符串而不是数字的原因:
Try it after removing the trailing newline, which is probably what's causing Perl to treat it as a string rather than a number: