IF语句的意外结果:"string"<= 72是真的吗?

kur*_*uki 0 perl

在下面的代码中,当我在输入处输入一些非数字字母(即.$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"; }
Run Code Online (Sandbox Code Playgroud)

Die*_*lla 6

这是因为如果无法将其转换为数字,则将其视为0.您应该先检查响应是否只有数字,或者以任何其他方式限制输入,以便只输入有效数字.一些事情:

print "invalid" if ($temp =~ /\D/);
Run Code Online (Sandbox Code Playgroud)

(如果$temp包含任何非数字字符,则打印无效.请注意,这可能使"+"和" - "无效,但您明白了).