MLMH
MLMH

Reputation: 141

Get the hash number

I am fairly new in Perl, and having worked all my life with R, there are something that I can't really can wrap my mind around.

I have an array of hashes. In all of the hashes, the keys are the same ones, but the values are different. I want to get the number of the hash that has a specific value in it, because in that hash there is another value that I want (and varies among different samples).

I don't know if this is the way that I should be addressing it, but is the one I can think of. Here is a piece of the array:

$VAR16 = {
           'harmonized_name' => 'geo_loc_name',
           'attribute_name' => 'geo_loc_name',
           'content' => 'not determined',
           'display_name' => 'geographic location'}
$VAR17 = {
           'harmonized_name' => 'env_package',
           'attribute_name' => 'env_package',
           'content' => 'missing',
           'display_name' => 'environmental package'}

In this example, I would want the 'content' value of the hash that has 'harmonized_name' = env_package

Upvotes: 0

Views: 60

Answers (1)

mpapec
mpapec

Reputation: 50637

You can use grep to filter all array elements which have 'harmonized_name' = env_package, and then check their values for content,

use strict;
use warnings;

my @AoH = (
  {
    'harmonized_name' => 'geo_loc_name',
    'attribute_name' => 'geo_loc_name',
    'content' => 'not determined',
    'display_name' => 'geographic location'
  },
  {
    'harmonized_name' => 'env_package',
    'attribute_name' => 'env_package',
    'content' => 'missing',
    'display_name' => 'environmental package'
  }
);

my @result = grep { $_->{harmonized_name} eq "env_package" } @AoH;

print $_->{content}, "\n" for @result;

output

missing

Upvotes: 6

Related Questions