Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Find all keys from a value in a hash

by Fletch (Bishop)
on Nov 09, 2021 at 20:55 UTC ( [id://11138648]=note: print w/replies, xml ) Need Help??


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

You might double check your data because a) $fruit{kiwi} is "green" not "red", and b) matching an arrayref as is in $fruit{apple} against a string value using eq isn't going to do anything useful (it will be checking that the stringified representation of the array reference is your target, which it's most likely not).

Addendum: I'm guessing you were actually searching for "green" but you mucked up your data, in which case you would have found the one value in $fruit{kiwi}. Your problem then is that if your value is an array ref you'd need to again grep the values therein. WHile you can handle this with something like below:

my( @found ) = grep { ( ref $fruit{ $_ } eq 'ARRAY' ? (grep { $_ eq $s +earch } @{ $fruit{ $_ } } ) : $fruit{$_} eq $search ) } keys %fruit;

Cleaner (but slightly less memory efficient) would be to always store an arrayref even for single items; then the code would collapse to just:

my( @found ) = grep { grep $_ eq $search, @{ $fruit{ $_ } } } keys %fr +uit;

Edit: Also another problem since you're catching the result of the grep with my( $found ) you're only going to see the first value returned from grep (any further matches will be silently discarded because you've only got the one scalar variable named in the list-context my declaration); you need to use an array instead if you want the list of all the matches found.

Another thought:, If your goal is to have something where you can check "What fruits can be color x?" then using a hash of hashes (HoH) can reduce this to a simple grep { exists $fruits{ $_ }->{$color} } keys %fruits. You'd need to set up %fruits a bit differently.

my %fruits = ( apple => { red => 1, green => 1 }, kiwi => { green => 1 }, banana => { yellow => 1 } );

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: Find all keys from a value in a hash
by Anonymous Monk on Nov 09, 2021 at 21:00 UTC
    Yes, sorry, my bad, I meant "green"!!!
Re^2: Find all keys from a value in a hash
by Anonymous Monk on Nov 10, 2021 at 12:31 UTC
    Actually the idea is to have a hash look up table to translate the values, that's why the sample code, I will have in a sub routine and each item will be passed and matched, then the key returned.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-20 04:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found