Help - Search - Member List - Calendar
Full Version: Finding the value of a key in a hash
WorkTheWeb Forums > Webmaster Resources > Perl Beginner Help
Support our Sponsors!
Dave Adams
%vegetable_costs = (Beans => 300
Carrots => 200,
Apple => 250 );

To get the value of the key called Beans you use $vegetable_costs{Beans} .

How do you do the reverse and get the value of the key?

Anyone?

Wiggins d'Anconia
Dave Adams wrote:
QUOTE
%vegetable_costs  =    (Beans  => 300
Carrots => 200,
Apple  => 250 );

To get the value of the key called Beans you use $vegetable_costs{Beans} .

How do you do the reverse and get the value of the key?

Anyone?


Well you run into problems there, because the value may not be unique.

%vegetable_costs = ( Beans => 300,
Carrots => 200,
Apple => 250,
Asparagus => 300
);

Now it depends on the order of the hash which one you will hit first,
and order can't be relied on.

If you can guarantee unique values then one verbose way:

my $test_val = '300';
while (my ($key, $val) = each %vegetable_costs) {
if ($val eq $test_val) {
print "Vegetable with cost $val: $keyn";
last;
}
}

A non-verbose way is just to shift the values to be keys in a different
temporary hash and then use the same lookup. This has problems on large
hashes requiring lots of memory and for complex values as they can't be
used as keys (in most cases), but then the simple 'eq' operator above
isn't going to work on them either.

Basically you have entered the realm of demons...

http://danconia.org

John W. Krahn
Dave Adams wrote:
QUOTE
%vegetable_costs  =    (Beans  => 300
Carrots => 200,
Apple  => 250 );

Apples are a vegetable?

QUOTE
To get the value of the key called Beans you use $vegetable_costs{Beans} .

How do you do the reverse and get the value of the key?

If all the costs are unique:

my %cost_lookup = reverse %vegetable_costs;

print "$cost_lookup{300} costs 300.n";


If you expect that many vegetables have the same cost then:

my %cost_lookup;

push @{ $cost_lookup{ $vegetable_costs{$_} } }, $_ for keys %vegetable_costs;

print "The vegetable(s) @{$cost_lookup{300}} cost 300.n";



John
--
use Perl;
program
fulfillment


PHP Help | Linux Help | Web Hosting | Reseller Hosting | SSL Hosting
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2006 Invision Power Services, Inc.