views:

168

answers:

5

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.

+2  A: 

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

Maybe there's unexpected whitespace in $category?

Matthew Wilson
yes, the newline the user has to enter in <STDIN>. Chomp it away.
glenn jackman
+2  A: 
***@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 checking what $category actually is? Sometimes these things can slip by even the best of us... Perhaps it is lowercase, or something different altogether.

When I get unexpected errors, I tend to use a print with delimiters around what I want to print, so I know where it actually starts and ends (as opposed to what my mind might interpret).

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

Something else of note, is Data::Dumper:

use Data::Dumper;
print Dumper(\$category);
Matthew Scharley
+13  A: 

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> );
Alan Haggai Alavi
A: 

Comparing with eq works just fine. Maybe you should output the value of $category in your else-block to see what it really is? Enclose the output in quotes so you can see if there is any surrounding whitespace.

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

if (uc($category) eq 'N') {
Lars Haugseth
A: 

Here is how I would 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 );
    }
  }
}
Brad Gilbert