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".