【问题标题】:Get key details from the value through grep通过 grep 从值中获取关键细节
【发布时间】:2021-11-15 00:20:50
【问题描述】:

我正在尝试通过我拥有的哈希匹配grep 中的$country_value 变量来查找键名作为输出。

#!/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";

根据哈希值,我需要得到输出为IN,因为IN 的值是1,而$country_value1,这是我想要找出的。

但是,我得到的输出是0 而不是IN

有人可以帮忙吗?

【问题讨论】:

标签: perl grep hashmap


【解决方案1】:

在您的代码中,values 返回对数组的引用。您需要取消对它的引用才能获得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";

打印:

IN

【讨论】:

    猜你喜欢
    • 2011-12-28
    • 2021-04-26
    • 2017-10-27
    • 2021-03-23
    • 1970-01-01
    • 2020-08-11
    • 2014-06-17
    • 1970-01-01
    • 2016-10-05
    相关资源
    最近更新 更多