in reply to Re^2: Hash from prompt
in thread Hash from prompt
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, |
|
|---|