2

我正在尝试合并两个哈希。好吧,我可以合并,但输出不是我想要的:

这是我的代码:

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。我想做的另一件事是,如果有任何重复的键,那么它应该给我一条警告消息。但它没有给我任何信息。正如我们在这里看到的,我们在两个哈希中都有阿拉哈巴德。

谢谢

4

3 回答 3

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 ];

}
于 2012-09-25T07:48:48.637 回答
2

该行if (exists $ref{$k}) {是错误的,如果您将其放在use strict; use warnings;脚本的开头,您可以看到它。

此外,这一行应该是if (exists $friends_place{$k}) {产生关于重复键的消息。

于 2012-09-25T08:09:45.183 回答
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]
于 2012-09-25T07:51:57.323 回答