2012-01-26 75 views
0

我有一個散列表,然後我嘗試將其添加到較大的散列表(如果唯一),但是我遇到了語法問題並且保留不小心調用值或創建哈希散列。所有我想要做的是反過來:perl:將散列對添加到較大的散列

(The actual $hash key) => $hash{$key}; 

$compound_hash{$key} = $hash{$key}; 


目前我有:

if ($file_no == 0){ 
      while (my ($key, $value) = each %hash){ 
        $compound_hash{$key} = $value; 
      }  

    }else{ 
      while (my ($key, $value) = each %compound_hash){ 

        if (exists $hash{$key}){ 
          print "$key: exists\n"; 
          $compound_hash{$key} .= ",$hash{$key}"; 
        }else{ 
          print "$key added\n"; 
          XXXXXXX 
        } 

最終的結果是連接到哈希值每行的結尾,製作一個.csv,即

 abc,0,32,45 
    def,21,43,23 
    ghi,1,49,54 

回答

3

它很難說完全是,但我認爲你正在尋找的是這樣的:

for my $key (keys %hash) { # for all new keys 
    if (exists $compound_hash{$key}) { # if we have seen this key 
      $compound_hash{$key} .= ",$hash{$key}" # append it to the csv 
    } 
    else { 
      $compound_hash{$key} = $hash{$key} # otherwise create a new entry 
    } 
} 

在我自己的代碼,我可能會設置%compound_hash將最初使用數組引用,這是然後在數據填充後加入字符串。

for my $key (keys %hash) { 
    push @{ $compound_hash{$key} }, $hash{$key} 
} 

再後來

for my $value (values %compound_hash) { 
    $value = join ',' => @$value 
} 

這將在不是重複數據附加到包含在所述化合物散列串更加有效。

+0

謝謝,這是非常有幫助的。 – Daniel 2012-02-01 14:48:47