for ( ;; ) {
print "Command> ";
$result = <STDIN>;
print "\n";
$answer = 0;
if ( $result == "add" ) {
for ( $counter = 1; $counter >= 1; $counter++ ) {
print "Enter the $counter th number: ";
$NumberToAdd = <STDIN>;
if ( $NumberToAdd != "NONE" ) {
$answer = $answer + $NumberToAdd;
} else {
print "\n";
last;
}
}
} elsif ( $result == "subtract" ) {
for ( $counter = 1; $counter >= 1; $counter++ ) {
print "Enter the $counter th number: ";
$NumberToSub = <STDIN>;
if ( $NumberToSub != "NONE" ) {
$answer = $answer - $NumberToSub;
} else {
print "\n";
last;
}
}
} elsif ( $result == "quit" ) {
last;
} else {
print "Error. Please enter add, subtract, or quit, and press Enter. \n";
}
print "The answer to your operation was: $answer \n";
}
现在,如果你在终点线输入quit,它仍然会进入第一个if语句。或者,如果您输入asdfsa,它仍将进入第一个if语句。等
编辑:新的,正确的工作代码如下所示:
for ( ;; ) {
print "Command> ";
chomp( $result = <STDIN> );
$answer = 0;
if ( $result eq 'add' ) {
for ( $counter = 1; $counter >= 1; $counter++ ) {
print "Enter number $counter to add: ";
chomp( $NumberToAdd = <STDIN> );
if ( $NumberToAdd ne 'NONE' ) {
$answer = $answer + $NumberToAdd;
} else {
last;
}
}
} elsif ( $result eq 'subtract' ) {
for ( $counter = 1; $counter >= 1; $counter++ ) {
if ( $counter == 1 ) {
print "Enter the first number to begin subtracting from: ";
chomp( $NumberToSubtractFrom = <STDIN> );
if ( $NumberToSubtractFrom eq 'NONE' ) {
last;
}
} elsif ( $counter != 1 ) {
$countertodisplay = $counter - 1;
print "Enter number $countertodisplay to subtract: ";
chomp( $NumberToSub = <STDIN> );
if ( $NumberToSub eq 'NONE' ) {
last;
} else {
$NumberToSubtractFrom = $NumberToSubtractFrom - $NumberToSub;
}
}
}
$answer = $NumberToSubtractFrom;
} elsif ( $result eq 'quit' ) {
last;
} else {
print "Error. Please enter add, subtract, or quit, and press Enter. \n";
}
print "The answer to your operation was: $answer \n";
}
答案 0 :(得分:6)
错误的运算符用作..
.. Perl有一些运算符的两个版本,一个用于数字,一个用于字符串比较。例如$ a == $ b比较两个数字是否相等,$ a eq $ b比较两个字符串。
详见Equality Operators;注意数字和 stringwise 这两个词。这些值是数字 -equal,即使它们是不同的字符串并且 stringwise - 不同。
以下是快速摘录:
如果左参数在数字上等于到右参数,则二进制“==”返回true。
如果左参数 stringwise equal 到右参数,则二进制“eq”返回true。
第一步是将==
的所有错误用法替换为eq
。
此外,代码应从$ result中删除尾随换行符,因为"foo" eq "foo\n"
为false。有关如何轻松完成此操作,请参阅chomp
。