2012-09-25 186 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()是通過在數組名前加上$來完成的。 –