LinuxQuestions.org
Help answer threads with 0 replies.
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie
User Name
Password
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!

Notices


Reply
  Search this Thread
Old 11-25-2014, 02:25 AM   #1
newbi2014
LQ Newbie
 
Registered: Nov 2014
Posts: 15

Rep: Reputation: Disabled
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!
 
Old 11-25-2014, 04:11 AM   #2
pan64
LQ Guru
 
Registered: Mar 2012
Location: Hungary
Distribution: debian/ubuntu/suse ...
Posts: 9,345

Rep: Reputation: 2747Reputation: 2747Reputation: 2747Reputation: 2747Reputation: 2747Reputation: 2747Reputation: 2747Reputation: 2747Reputation: 2747Reputation: 2747Reputation: 2747
see the exists and defined functions in perl: http://perldoc.perl.org/functions/exists.html
 
1 members found this post helpful.
Old 11-25-2014, 06:51 PM   #3
newbi2014
LQ Newbie
 
Registered: Nov 2014
Posts: 15

Original Poster
Rep: Reputation: Disabled
Hi @pan64 ,

Thank you! 'exists' worked!
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
LXer: String Matches in Regular Expressions LXer Syndicated Linux News 0 09-11-2011 01:50 AM
bash replace all matches of regex substring in string nickleus Linux - General 3 04-30-2011 11:08 AM
Taking User input and storing values in Hash in perl kdelover Programming 3 09-22-2009 02:02 AM
using read and setting variables from user input string tekgek Programming 1 11-27-2008 01:10 AM
parsing a user input string daphne19 Programming 1 04-22-2004 07:40 AM


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

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration