perl 在主哈希中创建子哈希

kupeojn6  于 2022-11-15  发布在  Perl
关注(0)|答案(2)|浏览(209)

我想在Perl中创建一个hash值的hash,而不必显式地写出所有内容。我知道我可以使用dclone来做类似这样的事情:

use Storable 'dclone';

my %main_hash = (
   A => {},
   B => {},
   C => {},
);

my %sub_hash = (
   a => [],
   b => [],
   c => [],
   d => [],
);

foreach my $main_key (keys %main_hash) {
   $main_hash{$main_key} = dclone {%sub_hash};
}

最终结果:

%main_hash:
   A => {
     a => [],
     b => [],
     c => [],
     d => [],
   },
   B => {
     a => [],
     b => [],
     c => [],
     d => [],
   },
   C => {
     a => [],
     b => [],
     c => [],
     d => [],
   },
);

有没有办法在不依赖dclone或其他导入的模块的情况下重复进行哈希插入?

roejwanj

roejwanj1#

你可以把%sub_hash声明放在循环中,并把它赋给主哈希值,每次循环迭代都是一个新的哈希值,你不需要dclone

my %main_hash = (
   A => {},
   B => {},
   C => {},
);

foreach my $main_key (keys %main_hash) {
    my %sub_hash = (
       a => [],
       b => [],
       c => [],
       d => [],
    );
   $main_hash{$main_key} = \%sub_hash;
}

use Data::Dumper;
print Dumper \%main_hash;

输出量:

$VAR1 = {
          'C' => {
                   'b' => [],
                   'a' => [],
                   'c' => [],
                   'd' => []
                 },
          'B' => {
                   'b' => [],
                   'a' => [],
                   'c' => [],
                   'd' => []
                 },
          'A' => {
                   'c' => [],
                   'd' => [],
                   'b' => [],
                   'a' => []
                 }
        };
f0brbegy

f0brbegy2#

请检查下面的代码片段,它利用两个索引生成一个散列--以符合您的问题。

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my %hash;

for my $main_key ( qw/A B C/ ) {
    for my $sub_key ( qw/a b c d/ ) {
        $hash{$main_key}{$sub_key} = [];
    }
}

say Dumper(\%hash);

输出量

$VAR1 = {
          'C' => {
                   'c' => [],
                   'd' => [],
                   'a' => [],
                   'b' => []
                 },
          'B' => {
                   'b' => [],
                   'a' => [],
                   'c' => [],
                   'd' => []
                 },
          'A' => {
                   'c' => [],
                   'd' => [],
                   'b' => [],
                   'a' => []
                 }
        };

相关问题