LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Ask User for Input and See if The String Matches Strings in Hash (https://www.linuxquestions.org/questions/linux-newbie-8/ask-user-for-input-and-see-if-the-string-matches-strings-in-hash-4175526424/)

newbi2014 11-25-2014 02:25 AM

Ask User for Input and See if The String Matches Strings in Hash
 
Hi,

I need help with Hash&Else if in Perl

In a hash, a=>1, b=>2, c=>3.
I need to write a script that will ask user for input. if the user typed in a or b or c, the output will display 1 or 2 or 3 respectively. Else, print "not valid".

Below is my code but I got errors.

#!/usr/bin/perl
use warnings;
my %data =(
'a' => 1,
'b' => 2,
'c' => 3
);

print "data: ";
chomp ($word = <STDIN>);

if ($word eq $data){
print ("$data{'$word'}\n");
} else {
print "not valid\n";
}

Thanks!

pan64 11-25-2014 04:11 AM

see the exists and defined functions in perl: http://perldoc.perl.org/functions/exists.html

newbi2014 11-25-2014 06:51 PM

Hi @pan64 ,

Thank you! 'exists' worked! :)


All times are GMT -5. The time now is 09:50 PM.