我遇到了一个看起来很简单的问题,但由于某种原因我无法解决它。基本上我的程序导致了一个无限循环,我不知道为什么。
这是我陷入的特定循环:
$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
要成为真的,循环应该终止吗?
这是整个代码供参考:
#!/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";