perl中的字符串匹配(if for循环中的语句)

时间:2013-10-18 21:43:14

标签: 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};
    }

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

1 个答案:

答案 0 :(得分:1)

更改

if ($delta eq '$somename'){

if ($delta eq $somename){

带有双引号(")的Perl字符串会插入$somename之类的变量,但带有单引号(')的字符串将不会这样做。

参考有关该文档的文档:http://perldoc.perl.org/perlop.html#Quote-and-Quote-like-Operators