通过grep从值中获取关键细节
Get key details from the value through grep
我试图通过我拥有的散列匹配 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_value
是 1
,这就是我想要找出的。
但是,我得到的输出是 0
而不是 IN
。
有人可以帮忙吗?
在您的代码中,values
returns 对数组的引用。您需要取消引用以获取 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
我试图通过我拥有的散列匹配 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_value
是 1
,这就是我想要找出的。
但是,我得到的输出是 0
而不是 IN
。
有人可以帮忙吗?
在您的代码中,values
returns 对数组的引用。您需要取消引用以获取 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