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

How to compare single character strings in Perl? Right now I'm trying 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 does not work. Regardless of the input, the else block is always executed.

+4
source share
5 answers

How do you take the value of $category ? If this is done as my $category = <STDIN> , you will need to compose a new line at the end:

 chomp( my $category = <STDIN> ); 
+13
source

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

Maybe there are unexpected spaces in the $ category?

+2
source
 ***@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:~$ 

Have you tried to check what $category is actually? Sometimes these things can slip even the best of us ... Perhaps these are lowercase letters or something completely different.

When I get unexpected errors, I usually use separator printing around what I want to print, so I know where it starts and ends (as opposed to what my mind could interpret).

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

Something else note, Data :: Dumper :

 use Data::Dumper; print Dumper(\$category); 
+2
source

Comparison with eq works just fine. Maybe you should print the value of $ category in your else block to find out what it really is? Include the output in quotation marks so you can see if there are any surrounding spaces.

Also, if you want comparisons to be case insensitive, try:

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

This is how I could write it if I could use 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 ); } } } 
0
source

Source: https://habr.com/ru/post/1286673/


All Articles