2012-09-25 185 views
2

我想合并两个哈希。好吧,我能合并,但输出是不是我希望它的方式:在perl中合并哈希

这里是我的代码:

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其次%城市第一。 我试图做的另一件事是,如果有任何重复的键,那么它应该给我一个警告信息。但它没有给我任何消息。正如我们在这里可以看到的,我们有Allahabad在这两个哈希。

感谢

+0

你只需要从第一哈希的所有键从第二所有键之前?或者,这些哈希值的键还需要以某种方式排序?无论使用哪种方式,您都需要使用数组来保持顺序,因为散列本身并不保留任何(插入或字母)。 – Thilo

回答

2

线if (exists $ref{$k}) {是错误的,你可以看到它,如果你把use strict; use warnings;在开始时的脚本。

此外,这种线应if (exists $friends_place{$k}) {以产生大约重复键的消息。

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

} 
+0

+1通知。它一直在使用if(定义$ city {$ friend}),镜像if(定义($ ARGV [0])),但它可以很好地保存击键。 – aschultz

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的,所以下面的代码是蟒蛇(应该是相当简单翻译成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] 
+0

这是Python如果我没有弄错,对吧? –

+1

@TudorConstantin:正如我的回答所指出的那样,我不太了解perl的具体细节。但是这两种语言的方法应该是一样的。正如在你的回答中指出的那样,我相信在Perl中,你会使用逗号运算符而不是加号运算符来合并字典并构建密钥列表;和len()是通过在数组名前加上$来完成的。 –