如何创建哈希的递归散列? (无限深) [英] How to create recursive hash of hash ? (With unlimited deep)
问题描述
请尝试创建一个复杂的数据结构。我知道如何做
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'
};
但是为了下一步,要做一个重新排序的散列哈希,我尝试:
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屋!