in reply to Re: Hash from prompt
in thread Hash from prompt

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

Replies are listed 'Best First'.
Re^3: Hash from prompt
by Athanasius (Cardinal) on Oct 13, 2014 at 04:37 UTC

    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,

Re^3: Hash from prompt
by rshoe (Novice) on Oct 13, 2014 at 04:35 UTC
    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.