我有以下代码
#!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};
}
代码的主要目标是定义单词列表。代码应将单词列表拆分为两个子列表,即@words1
和@words2
。要求用户输入姓名,然后进行秘密猜测。代码应检查@words2 中的名称,如果找到匹配项,则程序退出(带有打印测试)。由于某种原因,它没有按预期工作。我尝试进行一些基本的调试,一切看起来都不错,但是在函数 good_word 中,for 循环下的 if 语句永远不会返回 true,尽管我可以在调试中看到两者$somename
和 $delta 是相同的。有什么建议么??