Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fetch a hash ref from array of hashes by one of its values?

I have a array of hashes, each hash containing same keys but values are unique. On the basis of particular value, I need to store hash ref.

See the below example to understand it properly:

my @aoaoh = (
            { a => 1, b => 2 },
            { a => 3, b => 4 },
            { a => 101, b => 102 },
            { a => 103, b => 104 },
    );  

Now I will check if a hash key a contains value 101. If yes then I need to store the whole hash ref.

How to do that?

like image 759
Nikhil Jain Avatar asked Dec 03 '22 04:12

Nikhil Jain


1 Answers

my $key = "a";
my ($ref) = grep { $_->{$key} == 101 } @aoaoh;

or using List::Util's first():

use List::Util 'first';
my $ref = first { $_->{$key} == 101 } @aoaoh;
like image 69
Eugene Yarmash Avatar answered Dec 18 '22 12:12

Eugene Yarmash