0

所以我正在编写一个相对简单的程序,它会提示用户输入命令、加法、减法等,然后提示输入数字来完成该操作。一切都写好了,编译得很好,但是当我在(加、减等)中输入一个命令时,它并没有正确地比较它。没有进入if case的操作分支,而是进入了我添加的无效命令catch。这是包含声明和第一个 if 语句的代码的一部分。

my $command = <STDIN>;
my $counter = 1;
#perform the add operation if the command is add
if (($command eq 'add') || ($command eq 'a')){

    my $numIn = 0;
    my $currentNum = 0;
    #While NONE is not entered, input numbers.
    while ($numIn ne 'NONE'){
        if($counter == 1){
            print "\nEnter the first number: ";
        }else{
            print "\nEnter the next number or NONE to be finished.";
        }
        $numIn = <STDIN>;
        $currentNum = $currentNum + $numIn;

        $counter++;
    }

    print "\nThe answer is: #currentNum \n";

#perform the subtract operation if the command is subtract
}`

有谁知道为什么如果我输入添加它会跳过这个?

4

1 回答 1

5

$command 可能仍然附加了新行,因此 eq 将失败。因为“添加”!=“添加\n”

您可能会考虑只检查命令的第一个字母,例如使用正则表达式

$command =~ /^a/i

或在 $command 上使用 Chop 删除最后一个字符。

chop($command)
于 2012-09-07T23:23:41.627 回答