Antoine Antoine - 7 months ago 24
Perl Question

How to create recursive hash of hash ? (With unlimited deep)

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


But I don't know how to create


I try something like that :

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

So I succefully get :

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

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

%branch = %branchtmp;

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



A simple recursive solution:

#!/usr/bin/env perl

use strict;
use warnings;
use feature qw{say};
use Data::Dumper;

sub recursiveHash {
    my ($result, @rest) = @_;
    return $result unless @rest;

    my $nextTag = pop @rest;
    return recursiveHash( {$nextTag => $result}, @rest);

print Dumper(recursiveHash(3, 'level1', 'level2', 'level3'));


$VAR1 = {
          'level1' => {
                        'level2' => {
                                      'level3' => 3