我刚刚开始深入 perl 的疯狂世界,遇到了一个我似乎无法解决的问题。具体来说,我需要能够从一种哈希结构转换为另一种哈希结构,该结构使用键/值作为新的哈希键/值。
一个例子:
输入哈希:
my %original_hash = (
first_key => { some_key => "apples",
another_key => "chips",
#potentially more here
},
second_key => { more_of_same => "dogs",
its_another => "cats",
#potentially more here
}
);
输出哈希:
my %final_hash = (
some_key => {
apples => {
more_of_same => "dogs",
its_another => "cats",
}
} ,
another_key => {
chips => {
more_of_same => "dogs",
its_another => "cats",
}
}
);
是的,我确实希望在 final_hash 中重复 second_key 的数据,因为将有一个输入的 original_hashes 数组。第一个元素成为基本情况,所有其他元素都可以添加到该列表或从该列表中删除。
如果有人对如何执行此操作有任何建议,我们将不胜感激!
最佳答案
还有一种方法
my %final_hash;
my %tmp = %{$original_hash{first_key}};
my $val = $original_hash{second_key};
while ( my ($k,$v) = each %tmp) {
$final_hash{$k} = { $v => $val };
}
print Dumper (\%final_hash);
关于perl - 如何使用 key 将一个 Perl 散列转换为另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2500401/