Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: Find all keys from a value in a hash

by perlfan (Vicar)
on Nov 10, 2021 at 16:37 UTC ( #11138692=note: print w/replies, xml ) Need Help??

in reply to Find all keys from a value in a hash

You basically need to maintain a membership map as an index of values, the reverse look up referred to below:
my $search = "red"; my %fruit = ( 'apple' => ['red','green'], 'kiwi' => 'green', 'banana' => 'yellow', ); my %idx_fruit = ( 'red' => {'apple' => 1 }, 'green' => {'apple' => 1, 'kiwi' => 1 }, 'yellow' => {'banana' => 1}, );
Note: %idx_fruit is a hash, but contains members as hash references. This is to provide natural semantics for managing the membership sets and accessing values (e.g., delete, exists, etc). The value => 1 is meaningless, but might be useful for some additional meta data. You could even have them point to the reference of the member in %fruit for maximized fun.

Replies are listed 'Best First'.
Re^2: Find all keys from a value in a hash
by Anonymous Monk on Nov 11, 2021 at 14:11 UTC
    I came up with this:
    #!/usr/bin/perl use strict; use warnings; my $search = $ARGV[0] || ''; if(!$search) { print "\n\n Need a color word to search! \n\n"; exit; } my %fruit = ( 'apple' => ['red','green'], 'kiwi' => ['blue'], 'banana' => ['yellow'], 'avocato' => ['brown'], ); my ($result) = grep { grep { $_ eq $search } @{$fruit{$_}} } keys %fru +it; print "\n\n Result:::: --> $result \n\n";
      One thing that I like about this approach is to use anon ref's to array for all of the values if any key can be associated with more than a single color. This eliminates the checking of "if ref".

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11138692]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2022-01-24 20:09 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (65 votes). Check out past polls.