2013-10-18 64 views
-2

我有下面的代碼字符串在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都是相同的。 有什麼建議?

+1

永遠記得'使用strict',當它給你一個錯誤,修正錯誤,而不是註釋掉'使用strict' –

回答

1

變化

if ($delta eq '$somename'){ 

if ($delta eq $somename){ 

Perl語句用雙引號(")將插值像$somename變量,但字符串用單引號(')不會那麼做的。

參考文檔有關:http://perldoc.perl.org/perlop.html#Quote-and-Quote-like-Operators

+0

嗨凱文,感謝您的答覆。我改變了它,但仍然沒有工作。爲了便於理解,我有另一個腳本(幾乎相同),即$ somename = ; @ words2 = qw(john catherine alex); $ u = @ words2; for($ d = 0; $ d <$ u; $ d ++) \t { \t #print「當前數組中的名稱是@ words2 [$ d] \ n」; \t #print「somename的值是$ somename \ n」; \t $ delta = $ words2 [$ d]; \t print「delta的值是$ delta \ n」; \t if($ delta eq $ somename){print「test」; return 1;}} – user2896215

+0

在上面的腳本中,如果我輸入三個單詞中的任何一個,即john,catherine或alex,它就不會在屏幕上打印測試。看起來像是陳述由於某種原因失敗....即使如果我使用chomp($ somename)。 – user2896215