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 | |
|
Re^2: Find all keys from a value in a hash
by Anonymous Monk on Nov 10, 2021 at 12:31 UTC |