我有一個看起來非常簡單的問題,但由於某種原因,我無法解決它。基本上我的程序導致了一個無限循環,我不知道爲什麼。爲什麼這個簡單的while循環導致無限循環?
下面是具體的循環,我陷入在:
$response1 = false;
while($response1 == false){
print "Input column #: ";
$column = <STDIN>;
chomp($column);
if($column =~ m/^[0-9]+$/ and $column >= 0){
$response1 = true;
} else {
print "Invalid response\n";
}
}
當我運行它,它只是不斷問我"Input Column #"
。我給它一個數字,它接受數字,並且$ response變爲True,但while循環繼續前進,就好像$response
是假的。我是Perl新手,所以也許有一些我錯過了,但不while ($response == false)
表明,如果$response
成爲true,循環應該終止?
這裏是整個代碼以供參考:
#!/usr/bin/env perl
#Input control
my $response1;
my $response2;
my $response3;
my $quit = false;
#User input
my $column;
my $row;
my $continue;
#result
my $result;
#pascal subroutine
sub pascal{
$r = $_[0];
$c = $_[1];
if($r == 0 and $c == 0){
return 1;
} else {
return (($r-$c+1)/$c)*&pascal($r,($j-1));
}
}
print "Pascal Triangle Calculator\n";
while($quit == false){
$response1 = false;
$response2 = false;
$response3 = false;
while($response1 == false){
print "Input column #: ";
$column = <STDIN>;
chomp($column);
if($column =~ m/^[0-9]+$/ and $column >= 0){
$response1 = true;
} else {
print "Invalid response\n";
}
}
while($response2 == false){
print "Input row #: ";
$row = <STDIN>;
chomp($row);
if($row =~ m/^[0-9]+$/ and $row >= 0){
$response2 = true;
} else {
print "Invalid response\n";
}
}
$result = &pascal($row,$column);
print "The number at row $row and column $column of the Pascal triangle is $result\n";
while($response3 == false){
print "Calculate another? y/n: ";
$continue = <STDIN>;
chomp($continue);
if($continue == m/[yYnN]/){
$response3 = true;
} else {
print "Invalid response\n";
}
}
if($continue == m/[nN]/){
$quit = true;
}
}
print "Goodbye!\n";
使它與'use strict;使用警告;使用診斷;' –
'使用嚴格;使用警告;'確實會顯示錯誤(和其他)。始終使用這些! – ikegami
'true'和'false'在Perl中不是布爾值。沒有加載任何模塊或其他特殊功能,它們是裸字:字符串,在布爾上下文中爲true,但在數字上下文中爲'0'。 – TLP