CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner:
Access key hash using variable


New User

Jul 20, 2011, 2:29 PM

Post #1 of 2 (938 views)
Access key hash using variable Can't Post

Hi guys Frown

A variable is given from user to access the number of days for a specific month. Is it possible to use a variable as a key in a hash? Thanks in advance

# List here:
%month_days = ( "January" => 31, "February" => 28, "March" => 31, "April" => 30, "May" => 31, "June" => 30, "July" => 31, "August" => 31, "September" => 30, "October" => 31, "November" => 30, "December" => 31);

#Ask for month.
print "Enter month\n";
#Get number of days from hash

$numberDays = $month_days{"$month"}; #This is not working

print "Number of days in $month is $numberDays " #Does not print anything U_U




Veteran / Moderator

Jul 20, 2011, 2:55 PM

Post #2 of 2 (936 views)
Re: [nataT_T] Access key hash using variable [In reply to] Can't Post

You need to chomp the user input to remove the \n line terminator and you shouldn't quote single vars.

#Ask for month. 
print "Enter month\n";
#Get number of days from hash

$numberDays = $month_days{$month};

You should also keep in mind that Perl is case sensitive, so you should also add some checks to make sure the case of the user input is what you expect.

(This post was edited by FishMonger on Jul 20, 2011, 2:57 PM)


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives