2013-10-19 124 views
0

我有一個看起來非常簡單的問題,但由於某種原因,我無法解決它。基本上我的程序導致了一個無限循環,我不知道爲什麼。爲什麼這個簡單的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"; 
+4

使它與'use strict;使用警告;使用診斷;' –

+2

'使用嚴格;使用警告;'確實會顯示錯誤(和其他)。始終使用這些! – ikegami

+2

'true'和'false'在Perl中不是布爾值。沒有加載任何模塊或其他特殊功能,它們是裸字:字符串,在布爾上下文中爲true,但在數字上下文中爲'0'。 – TLP

回答

1

正如評論所說,它總是使用

use strict; 
use warnings; 

這將極大地幫助你特別是新時,Perl的好習慣。嚴格使用會迫使您清理代碼。您的代碼中的問題可以通過使用警告編譯指示來看到。如果我用警告運行你的代碼,我會得到以下輸出。

Argument "false" isn't numeric in numeric eq (==) at response_loop_test.pl line 4. 
Argument "false" isn't numeric in numeric eq (==) at response_loop_test.pl line 4. 

perl中的==用於比較數值。這樣的字符串將不會達到預期的效果。相反,您應該使用eq來比較字符串是否相等。

if ($response1 eq 'false') 

這將確保按照您的期望比較字符串的相等性。下面的鏈接描述了運營商的平等在Perl http://perldoc.perl.org/perlop.html#Equality-Operators

二進制「==」如果左側的參數在數值上等於 右邊的參數返回true。

如果左參數是字符串等於 的正確參數,則二進制「eq」返回true。

相關問題