Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my string equality test for a single character work?

How does one compare single character strings in Perl? Right now, I'm tryin to use "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]);
}

But it isn't working. Regardless of the input, the else block is always executed.

like image 210
Zian Choy Avatar asked Dec 04 '22 15:12

Zian Choy


2 Answers

How are you accepting the value of $category? If it is done like my $category = <STDIN>, you will have to chomp the newline at the end by:

chomp( my $category = <STDIN> );
like image 142
Alan Haggai Alavi Avatar answered May 21 '23 16:05

Alan Haggai Alavi


eq is correct. Presumably $category is neither "N" nor "V".

Maybe there's unexpected whitespace in $category?

like image 21
Matthew Wilson Avatar answered May 21 '23 16:05

Matthew Wilson