如何创建哈希的递归哈希?(无限深) [英] How to create recursive hash of hash ? (With unlimited deep)

查看:35
本文介绍了如何创建哈希的递归哈希?(无限深)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拜托,我尝试创建一个复杂的数据结构.我知道怎么做

Please, I try to create a complexe datastructure. I know how to do

$branch{'level1'}{'level2'}{'level3'}='leaf';

但我不知道如何创建

$branch{'level1'}....{'levelN'}='leaf';

我尝试过类似的事情:

$branch{'leaf'} = "1";
$branchREF = \%branch;
$branchtmp{'level3'} = $branchREF;

所以我成功地得到:

$VAR1 = 'level3';
$VAR2 = {
          'leaf' => '1'
        };

但是对于下一步,要对散列进行递归 N 散列,我尝试:

But for the next step, to do a recrusive N hash of hash, I try :

%branch = %branchtmp;

但结果完全错误... %branch 不是我所期望的.为了进行递归,我需要重用我的第一个 %branch 而不是创建一个新的.请问我该怎么办?

But the result is completly wrong... %branch is not what I'm expecting. To do my recursivity, I need to reuse my first %branch and not create a new one. How can I do please ?

A.

推荐答案

最简单的方法是记住 perl 如何处理多维数据结构.它是通过引用来实现的.所以你可能会发现从顶层开始更简单,而是作为一个哈希引用:

The simplest way is to remember how perl handles multi-dimensional data structures. It does so by references. So you may find it simpler to start at the top level, as a hash ref instead:

#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;

my @levels = qw ( level1 level2 level3 );

my $branch = {};

my $tail = pop(@levels);
my $cursor = $branch;
#iterate our levels
foreach my $level (@levels) { 
   #make a new anon-hash if there isn't one. 
   $cursor -> {$level} ||= {};
   #traverse down
   $cursor = $cursor->{$level};
}
#set a value
$cursor -> {$tail} = 'leaf';

print Dumper $branch;

输出:

$VAR1 = {
          'level1' => {
                        'level2' => {
                                      'level3' => 'leaf'
                                    }
                      }
        };

注意 - 您必须重置光标并重新遍历"才能再次执行此操作,但可以以类似方式遍历"结构.

Note - you would have to reset the cursor and 're-traverse' in order to do this again, but could 'walk' the structure in a similar fashion.

这篇关于如何创建哈希的递归哈希?(无限深)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆