in reply to Hash from prompt

Hello rshoe, and welcome to the Monastery!

You’re nearly there! You just need to move the line:

chomp $fruit;

to before the line:

my $fruits = $fruit_num{$fruit};

in which you access the hash. Why? After $fruit has been assigned the user’s input, its final character is a newline. With the newline still present, the hash lookup fails because the key apple\n is not the same as the key apple. chomp removes the trailing newline, so the user’s input then matches a hash key, and the hash lookup succeeds.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Hash from prompt
by rshoe (Novice) on Oct 13, 2014 at 04:26 UTC
    Athanasius: Thanks for your quick reply. The information you gave me makes sense. I made the change but I get an error that states: "Use of uninitialized value $fruits in concatenation (.) or string at asstl.pl line 28, <STDIN> line 1. Here is my updated code:
    ### create a hash my %fruit_num = ( apple => 3, bananas => 1, oranges => 2, ); ### promp the user to enter a key ### use the input to dispaly the value with that key. print "Which fruit do you whish to query? "; my $fruit = <STDIN>; chomp $fruit; my $fruits = $fruit_num{$fruit}; print "Number of" . $fruit . "is" . $fruits . " \n";
    I have even tried taken out the concatenation on the print line but still get an error. Any help would be appreciated. Randy

      You’re welcome. Here is a more robust version of the script which uses exists to test that the fruit entered is present as a key in the hash before trying to access its corresponding value:

      #! perl use strict; use warnings; my %fruit_num = ( apples => 3, bananas => 1, oranges => 2, ); print "Which fruit do you wish to query?\n"; my $fruit = <STDIN>; chomp $fruit; if (exists $fruit_num{$fruit}) { my $fruits = $fruit_num{$fruit}; print "Number of $fruit is $fruits\n"; } else { print "No data for fruit '$fruit'\n"; }

      Typical runs:

      14:35 >perl 1055_SoPW.pl Which fruit do you wish to query? apples Number of apples is 3 14:35 >perl 1055_SoPW.pl Which fruit do you wish to query? guavas No data for fruit 'guavas' 14:36 >

      Hope that helps,

      Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Athanasius: I just figured out what I did wrong. I typed in the wrong key. Everything works now. I appreciate all your help. Thank you; Randy

        rshoe: Further to Athanasius's reply: It is, in general, a very good idea to be suspicious of and to 'sanitize' (i.e., check, test, validate) input to your program even when the entity generating that input is you.