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? ";
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.
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 .
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.
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.
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;
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With