Search code examples
arraysperlhashreferenceperl-data-structures

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?


Solution

  • 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;