[英]perl: add hash pair to larger hash
I have a hash table generated which I am then trying to add to a larger hash table, (if unique) for each of multiple files but I'm having trouble with the syntax and keep accidentally calling values or creating a hash of hash. 我生成了一个哈希表,然后尝试将其添加到一个较大的哈希表(如果有的话),用于多个文件中的每个文件,但是我在语法上遇到麻烦,并一直不小心调用值或创建哈希哈希。 All I want to do is turn: 我要做的就是转向:
(The actual $hash key) => $hash{$key};
into 进入
$compound_hash{$key} = $hash{$key};
Currently I have: 目前我有:
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
}
The end result is to concatenate the hash value on to the end of each line, making a .csv ie 最终结果是将哈希值连接到每一行的末尾,从而创建一个.csv,即
abc,0,32,45
def,21,43,23
ghi,1,49,54
Its hard to tell exactly, but I think what you are looking for is something like this: 很难确切地说,但我认为您正在寻找的是这样的东西:
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
}
}
In my own code, I might setup %compound_hash
to be initially populated with array references, which are then joined down to strings once the data is filled. 在我自己的代码中,我可能会将%compound_hash
设置为最初使用数组引用填充,然后在填充数据后将其合并为字符串。
for my $key (keys %hash) {
push @{ $compound_hash{$key} }, $hash{$key}
}
and then later 然后再
for my $value (values %compound_hash) {
$value = join ',' => @$value
}
Which will be more efficient than repeatedly appending data to the strings contained in the compound hash. 这比将数据重复添加到包含在复合哈希中的字符串更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.