How can I get a hash link from an array of hashes with one of my values?

I have an array of hashes, each hash contains the same keys, but the values ​​are unique. Based on the specific value, I need to save the hash code.

See the example below to get it right:

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

Now I will check if the hash key contains a avalue 101. If so, then I need to save the entire hash code.

How to do it?

+3
source share
3 answers
my $key = "a";
my ($ref) = grep { $_->{$key} == 101 } @aoaoh;

or using List::Util first():

use List::Util 'first';
my $ref = first { $_->{$key} == 101 } @aoaoh;
+14
source

I used foreachto get Hash refas

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

, ,

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

( ),

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

The method firstis good and I would use it if I wanted to do it once or twice. But, if you want to do this many times, it's probably best to write a lookup table, for example:

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

Then you will find your link like this:

my $ref = $hash_lookup{ $a_or_b }{ $value };
+1
source

Source: https://habr.com/ru/post/1766344/


All Articles