Maximilien
Maximilien

Reputation: 49

Perl: using array to create hash of hash structure

within a loop I retreive

And I would like to create a hash of hash having as structure the array and set at the end the data retreived.

exemple if I have:

@array = ('a','b','c');
$dataname = 'my data';
$datavalue = '123';

I would like to have a hash as below:

%hash = (
     a => {
           b => {
                 c => {
                       'my data' => '123'
                      }
                }
          }
          );

But i didn't find anywhere how to do it.

Upvotes: 0

Views: 121

Answers (2)

Nullman
Nullman

Reputation: 4279

you can do it this way, its not the most efficient but it works

use Data::Dumper;

my @array = ('a','b','c');
my $dataname = 'my data';
my $datavalue = '123';

my $hash = {$dataname => $datavalue};

foreach my $item (reverse @array){
    $hash = {$item =>$hash};
}
my %hash =%$hash;
print Dumper(\%hash);

you will get the following output:

$VAR1 = {
          'a' => {
                   'b' => {
                            'c' => {
                                     'my data' => '123'
                                   }
                          }
                 }
        };

Upvotes: -1

ikegami
ikegami

Reputation: 385496

use Data::Diver qw( DiveVal );

DiveVal(\%hash, map \$_, @array, $dataname) = $datavalue;

Alternatively,

sub DiveVal :lvalue {
   my $p = \shift;
   $p = \( $$p->{$_} ) for @_;
   $$p
}

DiveVal(\%hash, @array, $dataname) = $datavalue;

Upvotes: 3

Related Questions