if语句不会在perl中捕获字符串

mas*_*ral 3 perl string-comparison

当一个人输入一个表示退出或退出的输入时,我试图让我的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";
            }      
}
}
Run Code Online (Sandbox Code Playgroud)

elsif (chomp($g) eq "quit" || chomp($g) eq "exit) {
Run Code Online (Sandbox Code Playgroud)

尽管多次尝试捕捉错误,但是线路并没有捕获.我试过打印出程序看到的东西无济于事.当我输入严格/警告退出时,我得到的回应是

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.
Run Code Online (Sandbox Code Playgroud)

我已经看过其他几个帖子,但是他们中没有任何内容似乎是造成这种情况的原因.我究竟做错了什么?

xxf*_*xxx 5

chomp命令删除尾随换行符,但作用于变量本身,其返回值是删除的字符数.通常,只需要chomp变量或表达式一次.由于perl中存在2种类型的比较运算符,< <= == != >= >对于数字,lt le eq ne ge gt对于字符串,我们应该在执行比较之前确定我们具有哪种值以避免触发警告.

$guess =~ m|^\d+$|如果$guess是正整数或0,则通过检查字符串化版本$guess仅由数字组成,该语句返回true .

由于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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)