Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple hash search by value

I have a simple hash, and would like to return the $key based on $value criteria. That is, for line 14, what code would I need to return the $key where the $value is "yellow"?

1  #!/usr/bin/perl
2
3  # This program creates a hash then
4  # prints out what is in the hash
5
6  %fruit = (
7   'apple' => ['red','green'],
8   'kiwi' => 'green',
9   'banana' => 'yellow',
10  );
11
12 print "The apple is @{$fruit{apple}}.\n";
13 print "The kiwi is $fruit{kiwi}.\n";
14 print "What is yellow? ";
like image 910
kurotsuki Avatar asked Nov 22 '11 03:11

kurotsuki


People also ask

What is the simplest hash function?

The easiest example of a cryptographic hash function is the Rabin function, modular squaring. It works like this: Take your input as a number (any digital data can easily be interpreted as a binary number). Square it.

How do you search a hash?

To search for a file that has a given md5, sha1 or sha256 just type in the hash under consideration in the main search box. Example, searching for the file with md5: 12602de6659a356141e744bf569e7e56 .

Can hash be used for searching?

Data retrieval Hashing uses functions or algorithms to map object data to a representative integer value. A hash can then be used to narrow down searches when locating these items on that object data map.

How hash value is calculated?

Hashing involves applying a hashing algorithm to a data item, known as the hashing key, to create a hash value. Hashing algorithms take a large range of values (such as all possible strings or all possible files) and map them onto a smaller set of values (such as a 128 bit number). Hashing has two main applications.


2 Answers

grep is the right tool for this job:

my @all_matches = grep { $fruit{$_} eq 'yellow' } keys %fruit;
print("$_ ") foreach @matching_keys;

my ($any_match) = grep { $fruit{$_} eq 'yellow' } keys %fruit;
like image 174
socket puppet Avatar answered Nov 12 '22 05:11

socket puppet


I'm not so sure that's easy to do efficiently with a one-way hash. The whole point of a hash is to convert the key into a value (or position of the value if you're looking under the covers). You can do an exhaustive search over all the values, collecting the keys as you go but that's not as efficient as a hash lookup.

In order to go the other way efficiently, you might want to consider a two-way hash, something like:

%fruit = (
    'apple' => ['red','green'],
    'kiwi' => 'green',
    'banana' => 'yellow',
);
%antifruit = (
    'red' => 'apple',
    'green' => ['apple','kiwi'],
    'yellow' => 'banana',
);
print "The apple is @{$fruit{'apple'}}.\n";
print "The kiwi is $fruit{'kiwi'}.\n";
print "A yellow thing is $antifruit{'yellow'}.\n";
like image 40
paxdiablo Avatar answered Nov 12 '22 06:11

paxdiablo