如何在不使用Perl中的键的情况下查找值是否存在于哈希中? [英] How to find if the value exists in hash without using key in perl?
本文介绍了如何在不使用Perl中的键的情况下查找值是否存在于哈希中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的哈希图
I have an hash map like this
my $name = 'AUS'; #dynamic values
my %hash = { 'a'=>{
'x'=> {
'1' =>'US'
'2' =>'UK'
}
'y'=>{
'1' =>'AFRICA'
'2' =>'AUS'
}
}
'b'=>{
'x' =>{
'1' =>'US'
'2' =>'UK'
}
}
};
我正在尝试查找名称是否在每个列的哈希中都是唯一的
I am trying to find whether name is unique in the hash for each column
foreach my $key(keys %hash)
{
if($name ne $hash{}{}{}) #is name unique in whole hash?
{
print "something";
}
else
{
print "nothing";
}
}
一切都很好,但是当涉及到键"b"时,它会检查AUS是否不存在并打印东西",但我也希望它也检查"a"键以查看是否具有"AUS"值.因此,如何检查$ name是否存在于整个散列中(我无法通过键值对使用find,因为我试图在每列中查找和打印)?
All is fine but when it comes to key 'b' it checks that AUS is not present and prints "something" but I want it to check the 'a' key too to see if has 'AUS' value. So,how to check whether $name exists in whole hash (i can't use find via key-value pair since i am trying to find and print in each column) ?
推荐答案
如果我理解正确,那么您需要这样的东西:
if I understand correctly you want something like this:
use strict;
use warnings;
my $name = 'AUS'; #dynamic values
my %hash = ( 'a'=>{
'x'=> {
'1' =>'US',
'2' =>'UK'
},
'y'=>{
'1' =>'AFRICA',
'2' =>'AUS'
}
},
'b'=>{
'x' =>{
'1' =>'US',
'2' =>'UK'
}
}
);
my @val = grep {$_ eq $name} map {my $x=$_; map {my $y=$_; map {$hash{$x}->{$y}->{$_}} keys %{$hash{$x}->{$_}}} keys %{$hash{$_}}} keys %hash;
if(@val == 0) {
print "$name not found";
}
elsif(@val == 1) {
print "$name is unique";
}
else {
print "$name is not unique";
}
这篇关于如何在不使用Perl中的键的情况下查找值是否存在于哈希中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文