Antoine Antoine - 6 months ago 13
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

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


But I don't know how to create

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


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...
%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.

Answer

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'));

Output:

$VAR1 = {
          'level1' => {
                        'level2' => {
                                      'level3' => 3
                                    }
                      }
        };
Comments