2013-07-16 41 views
0

我有一個散列結構,我希望將新值添加到現有值(不是使用新值更新)。
這是我的代碼。如果存在散列鍵,則將新值添加到現有值中

use strict; 
    use warnings; 
    my %hash; 
    while(<DATA>){ 
     my $line=$_; 
     my ($ID)=$line=~/ID=(.*?);/; 
     #make a hash with ID as key                                                                                    
     if (!exists $hash{$ID}){ 
      $hash{$ID}= $line; 
     } 
     else{ 
      #add $line to the existing value                                                                                  
     } 
    } 
    for my $key(keys %hash){ 
     print $key.":".$hash{$key}."\n"; 
    } 
    __DATA__ 
    ID=13_76; gi|386755343 
    ID=13_75; gi|383750074 
    ID=13_75; gi|208434224 
    ID=13_76; gi|410023515 
    ID=13_77; gi|499086767 
+0

歡迎來到StackOverflow。請閱讀以下內容並改進您的問題:http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist 對於初學者,請告訴我們您嘗試了什麼,以及爲什麼它不起作用。 –

回答

1
else{ 
     $hash{$ID} .= $line;                                                                                 
    } 
0

你應該存儲在陣列中的散列數據:

#!/usr/bin/env perl 

use strict; 
use warnings; 

# -------------------------------------- 

use charnames qw(:full :short ); 
use English qw(-no_match_vars); # Avoids regex performance penalty 

use Data::Dumper; 

# Make Data::Dumper pretty 
$Data::Dumper::Sortkeys = 1; 
$Data::Dumper::Indent = 1; 

# Set maximum depth for Data::Dumper, zero means unlimited 
local $Data::Dumper::Maxdepth = 0; 

# conditional compile DEBUGging statements 
# See http://lookatperl.blogspot.ca/2013/07/a-look-at-conditional-compiling-of.html 
use constant DEBUG => $ENV{DEBUG}; 

# -------------------------------------- 

my %HoA =(); 
while(my $line = <DATA>){ 
    if(my ($ID) = $line =~ m{ ID \= ([^;]+) }msx){ 
    push @{ $HoA{$ID} }, $line; 
    } 
} 
print Dumper \%HoA; 


__DATA__ 
ID=13_76; gi|386755343 
ID=13_75; gi|383750074 
ID=13_75; gi|208434224 
ID=13_76; gi|410023515 
ID=13_77; gi|499086767 
1

所有你需要的是$hash{$ID} .= $line;。沒有if-elses。 如果散列中沒有密鑰$ID,它將創建一個,並將$line連接爲空字符串,從而得到您所需要的。

相關問題