0

私は非常に単純に見える問題を抱えていますが、何らかの理由で回避できません。基本的に、私のプログラムは無限ループを引き起こしていますが、その理由はわかりません。

これが私が巻き込まれている特定のループです:

$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は false であるかのように進み続けます。私は Perl を初めて使用するので、何か不足している可能性がありますが、true になる場合にループを終了する必要がある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";
4

1 に答える 1

1

コメントで述べたように、常に使用することをお勧めします

use strict;
use warnings;

これは、特に Perl を初めて使用する場合に非常に役立ちます。厳密に使用すると、コードを整理する必要があります。コードの問題は、use warnings プラグマで確認できます。警告付きでコードを実行すると、次の出力が得られます。

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.

==in perl は数値の比較に使用されます。そのような文字列と比較すると、望ましい効果はありません。代わりに、eq文字列が等しいかどうかを比較するために使用する必要があります。

if ($response1 eq 'false')

これにより、文字列の等価性の比較が期待どおりに機能することが保証されます。次のリンクでは、perl http://perldoc.perl.org/perlop.html#Equality-Operatorsの等価演算子について説明しています。

バイナリ "==" は、左の引数が右の引数と数値的に等しい場合に true を返します。

バイナリ "eq" は、左の引数が右の引数と文字列的に等しい場合に true を返します。

于 2013-10-19T20:58:55.187 に答える