5

I've been struggling with assigning as variable to a key in Perl. What I'm trying to do is prompt the user to input a value to be held in a variable that is used as a key to access and print a value held in a hash table. The following code helps illustrate my problem:

my $key = 0;
print( "Enter the value for your key\n" );
$key = <>;
my %hash = (
   a => "A",
   b => "B",
);
    print( $hash{$key} );

The problem is that print( $hash{$key} ); prints nothing to the screen, yet printf( $hash{"a"}; does; I do not understand that. Any help and clarification will be greatly appreciated. Thanks in advance.

Axeman
  • 29,660
  • 2
  • 47
  • 102
wafflesausage
  • 295
  • 5
  • 14
  • 1
    possible duplicate of [I'm looking for some clarification on chomp](http://stackoverflow.com/questions/7290445/im-looking-for-some-clarification-on-chomp) – Zaid Sep 12 '11 at 17:57

1 Answers1

12

$key is ending up getting set to (for instance) "a\n", not "a". Use the chomp builtin to remove the trailing newline:

$key = <>;
chomp $key;
...
print $hash{$key};