Gossamer Forum
Home : General : Perl Programming :

Listing out a hash

Quote Reply
Listing out a hash
Hi,

I am new to Perl and got this small thing I have to do at work so here it goes:

I got a hash called education with the following structure:

%education = ();
$education{high} = "200";
$education{college} = "201";
$education{master} = "202";
$education{post} = "203";
$education{phd} = "204";

the numbers 200 and so is from the id in my database.

I want to list out the list (text based) like this:

1. high
2. college
3. master
4. post
5. phd

Select a number (1-5):

And the user should enter one (or several numbers separated by a comma) like this 1,3,5 and the system should then know that 1 = 200 and 3 - 202 and 5 = 204

I do now have it so the system separates the numbers but it can't connect the 1 with 200. Is there an easy way to do this?

Any ideas?


J0sh
Quote Reply
Re: [j0sh] Listing out a hash In reply to
http://learn.perl.org/ may be useful.

How does this work for you? There are quite a few solutions but here's one... that's not too efficient but fairly clear. (is there a problem with adding 199 to the input from the user?)

Code:
%education = ();
$education{high} = "200";
$education{college} = "201";
$education{master} = "202";
$education{post} = "203";
$education{phd} = "204";

%lookup;
foreach my $level ( values %education ) {
$lookup{$level - 199} = $level;
};

# display the structure. Just debug info and can be deleted
use Data::Dumper; print Dumper \%lookup;
Quote Reply
Re: [j0sh] Listing out a hash In reply to
One approach is to use an array to translate the numeric input to a keyword for hash lookup. This is also useful in displaying the menu . . .


my @levels = ("high","college","master","post","phd");

my %education = ();
$education{high} = "200";
$education{college} = "201";
$education{master} = "202";
$education{post} = "203";
$education{phd} = "204";
:
:
for $level(1..(@levels))
{
print "\t$level\. $levels[$level-1]\n";
}
:
:
my $level = scalar(@levels);
print "Please select: \(1 - $level) ";

my $answer = <STDIN>;
my @answers = $answer =~ /(\w)/g;

foreach(@answers)
{

$level = @levels[$_-1];
print "$level\tis $education{$level}\n";
}


hope this helps.