开发者

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

开发者 https://www.devze.com 2023-01-17 04:56 出处:网络
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.

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?


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;


Earlier, I was using foreach for fetching the Hash ref like

foreach my $href (@aoaoh){
     foreach my $hkeys(keys %{$href}){
           if(${$href}{$hkeys} == 101){
              my $store_ref = $href;
           }
     }
}

Now after taking help from eugene, i can do it like

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

or in general way (when we dont know the key) then use

my ($hash_ref) = grep { grep { $_ == 101 } values %$_ } @aoaoh; 


The first method is fine and what I'd use if I only wanted to do this once or twice. But, if you want to do this many times, it's probably better to write a lookup table, like so:

my %hash_lookup;
foreach my $h ( @aoaoh ) { 
    foreach my $k ( keys %$h ) { 
        $hash_lookup{$k}{ $h->{ $k } } = $h;
    }
}

Then you find your reference like so:

my $ref = $hash_lookup{ $a_or_b }{ $value };
0

精彩评论

暂无评论...
验证码 换一张
取 消