2009-06-24 158 views
4

如何比較Perl中的單個字符字符串?現在,我試着用「eq」:爲什麼我的字符串不等於單個字符的測試工作?

print "Word: " . $_[0] . "\n"; 
print "N for noun, V for verb, and any other key if the word falls into neither category.\n"; 
$category = <STDIN>; 

print "category is...." . $category . "\n"; 

if ($category eq "N") 
{ 
    print "N\n"; 
    push (@nouns, $_[0]); 
} 
elsif($category eq "V") 
{ 
    print "V\n"; 
    push (@verbs, $_[0]); 
} 
else 
{ 
    print "Else\n"; 
    push(@wordsInBetween, $_[0]); 
} 

但它不工作。無論輸入如何,else塊都始終執行。

回答

13

你怎麼接受的$category價值?如果是喜歡做my $category = <STDIN>,你將不得不在年底的Chomp換行符:

chomp(my $category = <STDIN>); 
2

eq是正確的。推測$類別既不是「N」也不是「V」。

也許在$ category中有意想不到的空白?

+0

是,用戶在進入換行符。把它趕走。 – 2009-06-25 11:26:19

2
***@S04:~$ perl -we '$foo = "f"; print "Success\n" if ($foo ne "e")' 
Success 
***@S04:~$ perl -we '$foo = "f"; print "Success\n" if ($foo eq "e")' 
***@S04:~$ 

您是否試過檢查$category究竟是什麼?有時候,即使是我們最好的人,這些東西也可能會滑落...也許它是小寫字母,或者完全不同的東西。當我收到意想不到的錯誤時,我傾向於在打印時使用帶有分隔符的打印,因此我知道它實際開始和結束的位置(與我的想法可能解釋的相反)。

print "|>${category}<|"; 

別的東西值得注意的是Data::Dumper

use Data::Dumper; 
print Dumper(\$category); 
0

EQ工作得很好比較。也許你應該在你的else塊中輸出$ category的值,看看它到底是什麼?將輸出用引號括起來,以便查看是否有任何周圍的空白。

另外,如果你想比較是不區分大小寫的,請嘗試:

if (uc($category) eq 'N') { 
0

這是我會怎麼寫呢,如果我可以用Perl 5.10。

#! perl 
use strict; 
use warnings; 
use 5.010; 

our(@nouns, @verbs, @wordsInBetween); 
sub user_input{ 
    my($word) = @_; 
    say "Word: $word"; 
    say "N for noun, V for verb, and any other key if the word falls into neither category."; 
    $category = <STDIN>; 
    chomp $category; 

    say "category is.... $category"; 

    given(lc $category){ 
    when("n"){ 
     say 'N'; 
     push(@nouns, $word); 
    } 
    when("v"){ 
     say 'V'; 
     push(@verbs, $word); 
    } 
    default{ 
     say 'Else'; 
     push(@wordsInBetween, $word); 
    } 
    } 
} 
相關問題