There's more than one way to do things | |
PerlMonks |
Re: Find all keys from a value in a hashby Fletch (Bishop) |
on Nov 09, 2021 at 20:55 UTC ( [id://11138648]=note: print w/replies, xml ) | Need Help?? |
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:
Cleaner (but slightly less memory efficient) would be to always store an arrayref even for single items; then the code would collapse to just:
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.
The cake is a lie.
In Section
Seekers of Perl Wisdom
|
|