If statement won't catch a string in perl

时间:2018-03-25 20:31:19

标签: perl string-comparison

I'm trying to get my if statement to catch when a person enters an input that says quit or exit but it isn't. Here is my code

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";
            }      
}
}

The

elsif (chomp($g) eq "quit" || chomp($g) eq "exit) {

line is not catching despite numerous attempts to catch the error. I've tried printing off what the program is seeing to no avail. What I get in response when I type in quit from the strict/warnings is that

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.

I've looked at several of the other posts on this but nothing from them seems to be whats causing this. What am I doing wrong?

1 个答案:

答案 0 :(得分:5)

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

如果$guess =~ m|^\d+$|是正整数或0,$guess语句返回true,方法是检查$guess的字符串化版本是否仅由数字组成。

由于rand返回小数0 <= x < 1,因此rand 25将返回一个数字 0 <= x < 25因此永远无法联系到25int会将数字向下舍入为零,因此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
        }
    }
}