Home > other >  Get key details from the value through grep
Get key details from the value through grep

Time:09-22

I am trying to find the key name as output by matching $country_value variable in grep through the hash I have.

#!/usr/bin/perl -w

use strict;
use warnings;

my $country_value = 1;

my $country = {
    'IN' => [
              1,
              5
            ],
    'US' => [
              2,
              6
            ],
    'UK' => [
              3,
              7
            ]
};

my $country_details = grep { $_ eq $country_value } values %{$country};

print $country_details;

print "\n";

As per the hash, I need to get the output as IN because the value of IN is 1 and the $country_value is 1, which is what I am trying to find out.

But, I get the output as 0 instead of IN.

Can someone please help?

CodePudding user response:

In your code, values returns a reference to an array. You need to dereference that to get a list for grep.

use warnings;
use strict;

my $country_value = 1;

my $country = {
    'IN' => [
              1,
              5
            ],
    'US' => [
              2,
              6
            ],
    'UK' => [
              3,
              7
            ]
};

my $country_details;
for my $name (keys %{$country}) {
    if (grep { $_ == $country_value } @{ $country->{$name} }) {
        $country_details = $name;
        last;
    }
}
print $country_details, "\n";

Prints:

IN
  • Related