perl - 如何使用 key 将一个 Perl 散列转换为另一个?

标签 perl hash key

我刚刚开始深入 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/

相关文章:

perl - cpan 命令给出错误 "Can' t locate B.pm in @INC"

perl - 用 perl 替换指定行号上的模式

c - C 中的字符串/整数关联

Java用密码加密文件

java - JButton KeyBinding 和 setActionCommand

regex - Perl 正则表达式将 {a, b, c, ..., x} 转换为 (a|b|c|...|x)

linux - 将 "file"linux 命令应用于 Perl 中的二进制缓冲区

php - bcrypt 内置 c 代码

ruby-on-rails - 如何在哈希中获取最小键值对

datetime - 带有日期的流畅 NHibernate 复合键