2012-09-07 100 views
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 
}` 

有没有人知道为什么如果我输入添加它跳过这?

回答

5

$命令可能还有新的行附加到它,所以eq将失败。因为“添加”!=“添加\ n”

你可能会考虑只检查你的命令的第一个字母,说用正则表达式

$command =~ /^a/i 

或使用印章上$命令删除的最后一个字符。

chop($command) 
+4

'chomp(my $ command = );''比较习惯,我会说。 ) – raina77ow

+1

同意,但我认为在这种情况下较小的步骤可能会使原因和结果更清晰一些。 –

+0

将chomp添加到完美固定的行中。谢谢! – Bigby

相关问题