我正在尝试合并两个哈希值。好吧,我能够合并,但输出不是我想要的方式:
这是我的代码:
my %friend_list = (
Raj => "Good friend",
Rohit => "new Friend",
Sumit => "Best Friend",
Rohini => "Fiend",
Allahabad => "UttarPradesh",
);
my %city = (
Bangalore => "Karnataka",
Indore => "MadhyaPradesh",
Pune => "Maharashtra",
Allahabad => "UP",
);
my %friends_place = ();
my ($k, $v);
foreach my $ref (\%friend_list, \%city) {
while (($k,$v) = each (%$ref)) {
if (exists $ref{$k}) {
print"Warning: Key is all ready there\n";
next;
}
$friends_place{$k} = $v;
}
}
while (($k,$v) = each (%friends_place)) {
print "$k = $v \n";
}
从这个o / p是
Raj=Good friend
Indore=MadhyaPradesh
Rohit=new Fiend
Bangalore=Karnataka
Allahabad=UttarPradesh
Sumit=Best Friend
Pune=Maharashtra
Rohini =Fiend
但我想首先打印%friend_list ,然后打印%city 。 我试图做的另一件事是,如果有任何重复的密钥,那么它应该给我一个警告信息。但它没有给我任何信息。正如我们在这里看到的,我们在哈希中都有阿拉哈巴德。
谢谢
答案 0 :(得分:3)
尝试:
my %firend_list = (
Raj => "Good friend",
Rohit => "new Fiend",
Sumit => "Best Friend",
Rohini => "Fiend",
Allahabad => "UttarPradesh",
);
my %city = (
Bangalore => "Karnataka",
Indore => "MadhyaPradesh",
Pune => "Maharashtra",
Allahabad => "UP",
);
#merging
my %friends_place = ( %friend_list, %city );
并且,警告:
foreach my $friend( keys %friend_list ){
print"Warning: Key is all ready there\n" if $friend ~~ [ keys %city ];
}
答案 1 :(得分:2)
第if (exists $ref{$k}) {
行是错误的,如果您将use strict; use warnings;
放在脚本的开头,则可以看到它。
此外,此行应为if (exists $friends_place{$k}) {
以生成有关重复键的消息。
答案 2 :(得分:1)
由于哈希是无序的,您需要使用数组来存储排序:
my %friends_place = (%firend_list, %city);
my @friends_place_keyorder = ((keys %firend_list), (keys %city));
if ((scalar keys %friends_place) != (scalar @friends_place_keyorder)) {
print 'duplicate key found';
}
foreach (@friends_place_keyorder) {
print "$_ = $friends_place{$_}\n";
}
编辑:我在python中的原始解决方案,为了历史目的留在这里:
由于哈希是无序的,您需要使用数组来存储排序。我不知道perl,所以下面的代码是python(转换为perl应该相当简单):
friend_list = ...
city = ...
friends_place = dict(friend_list.items() + city.items())
friends_place_keyorder = friend_list.keys() + city.keys()
# detect duplicate keys by checking their lengths
# if there is duplicate then the hash would be smaller than the list
if len(friends_place) != len(friends_place_keyorder):
print "duplicate key found"
# iterate through the list of keys instead of the hashes directly
for k in friends_place_keyorder:
print k, friends_place[k]