Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^3: Hash from prompt

by Athanasius (Archbishop)
on Oct 13, 2014 at 04:37 UTC ( [id://1103588]=note: print w/replies, xml ) Need Help??


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,

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1103588]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-03-29 11:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found