2012-01-26 76 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