How Does One Use a Variable as a Hash Key in Perl?
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 p开发者_高级运维rint 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.
$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};
精彩评论