我试图让我的 if 语句在有人输入表示退出或退出但事实并非如此的输入时捕捉。这是我的代码
use strict;
use warnings;
my $g=0;
my $rn = int(rand(25));
until ($g == $rn) {
$g = <STDIN>;
if ($g == $rn) {
print "You got it";
} elsif (chomp($g) eq "quit" || chomp($g) eq "exit") {
print "it triggered";
} elsif ($g > $rn) {
print "incorrect its lower";
} elsif ($g <$rn) {
print "incorrect its higher";
} else {
print "end";
}
}
}
elsif (chomp($g) eq "quit" || chomp($g) eq "exit) {
尽管多次 try catch 错误,但行未捕获。我试过打印程序看到的内容但无济于事。当我从 strict/warnings 中输入 quit 时,我得到的响应是
argument "quit\n" isn't numeric in numeric eq (==) at ./program24.pl line 30, <STDIN> line 1.
argument "quit" isn't numeric in numeric gt (>) at ./program24.pl line 36, line 1.
我已经查看了其他几篇关于此的帖子,但似乎没有任何内容是导致此问题的原因。我做错了什么?
chomp
命令删除尾随换行符,但作用于变量本身,其返回值是删除的字符数。所以通常情况下,只需要 chomp
一个变量或表达式一次。由于 perl 中有两种类型的比较运算符,< <= == != >= >
对于数字,lt le eq ne ge gt
对于字符串,我们应该在执行比较之前确定我们有什么样的值,以避免触发警告。
$guess =~ m|^\d+$|
如果 $guess
则语句返回真是正整数或 0,通过检查 $guess
的字符串化版本仅由数字组成。
自 rand
返回小数 0 <= x < 1
然后rand 25
将返回一个数字
0 <= x < 25
所以25
永远达不到。 int
会将数字向下舍入为零,因此 int rand 25
将返回 (0,1,2,...,22,23,24)
之一.获取(1,2,...,25)
我们需要添加 1
.
单字母变量,如 $g
通常是一个坏主意,因为它们不传达变量的含义,并且如果它在代码中变得普遍,则以后更难重命名。我已将其替换为 $guess
.在 perl 中,唯一普遍接受的单字母变量是 $a
和 $b
它们是全局的并用于比较函数,以及 perl 预定义变量,如 $_
, $@
等,记录在 perldoc perlvar 中
#!/usr/bin/perl
use strict;
use warnings;
my $guess = 0;
my $int_max = 25;
my $rn = int(rand($int_max)) + 1;
print "I have picked a number between 1 and $int_max, can you guess it?\n";
until ($guess == $rn) {
chomp ($guess = <STDIN>);
if ( $guess =~ m|^\d+$| ) {
# Answer is an integer
if ( $guess == $rn ) {
print "You got it!\n";
} elsif ( $guess > $rn ) {
print "Too high, try again.\n";
} elsif ( $guess < $rn ) {
print "Too low, try again.\n";
}
} else {
# Anything else
if ('quit' eq $guess or 'exit' eq $guess) {
print "Exiting...\n";
exit 0;
} else {
print "Unclear answer : '$guess' : try again!\n";
$guess = 0; # So the equality test does not warn
}
}
}