我有下面的代碼字符串在Perl的匹配(如果在循環語句)
#!C:\Perl64\bin -w
#use strict; use warnings;
init_words();
print "What is your name Mr. \n";
$name = <STDIN>;
chomp ($name);
if ($name =~ /^randal\b/i){
print "Hello, Randal, How are you doing \n";
} else {
print "Hello, $name!\n";
print "Tell the secret word\n";
$guess = <STDIN>;
chomp ($guess);
while (!good_word ($name,$guess)) {
print "Wrong, please try again\n";
$guess = <STDIN>;
chomp ($guess);
}
}
sub init_words {
open (WORDSLIST, "wordslist.txt") || die "can't open wordslist: $!";
$k = 1;
$a = 0;
$b = 0;
while (defined ($name = <WORDSLIST>)) {
if ($k % 2 == 0) {
chomp ($name);
$words1[$a] = $name;
++$k;
++$a;
} else {
chomp ($name);
$words2[$b] = $name;
++$k;
++$b;
}
}
close (WORDSLIST) || die "couldn't close wordlist: $!";
}
sub good_word {
my ($somename, $someguess) = @_;
$somename =~ s/\W.*//;
$somename =~ tr/A-Z/a-z/;
if ($somename eq "randal") {
return 1;
} else {
#$n = 0;
#words1 has secret words.
#words2 has names.
$t = scalar @words1;
$u = scalar @words2;
print "the words1 array is @words1 \n";
print "the words2 array is @words2 \n";
for ($d = 0; $d < $u; $d++) {
#print "currently name in array is @words2[$d]\n";
print "The value of somename is $somename \n";
$delta = $words2[$d];
print "The value of delta is $delta";
#use strict; use warnings;
if ($delta eq '$somename') {
print "test";
return 1;
}
}
#print "The final value of d is $d";
#print " The final value of array is @words1[$d]";
#if ("groucho" eq $someguess) {
#return 1;}
#else{
#while ($n < $t){
#if (@words1[$n] eq $someguess) {
#return 1;}
#else { ++$n};
}
代碼的主要目標是有wordslist定義。該代碼應該將單詞表分成兩個子列表,即@words1
和@words2
。用戶被要求輸入姓名,然後進行祕密猜測。代碼應該檢查@ words2中的名稱,如果找到匹配程序退出(通過打印測試)。 出於某種原因,它不能按預期工作。我試着做一些基本的調試,一切都看起來不錯,但在函數good_word中,for循環下的if語句永遠不會返回true,儘管我可以在調試中看到$somename
和$ delta都是相同的。 有什麼建議?
永遠記得'使用strict',當它給你一個錯誤,修正錯誤,而不是註釋掉'使用strict' –