2009-06-24 202 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); 
    } 
    } 
} 
相关问题