Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Find all keys from a value in a hash

by perlfan (Vicar)
on Nov 10, 2021 at 16:37 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2024-03-28 14:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found