perlmultidimensional-arrayhashcomplex-data-types

Perl - how to create dynamic multi level hash using array of elements as keys


I like to create a multi level hash by using an array that stores the elements to form the multi level keys. Example:

@elements = ('level1','level2','level3');

And want something like this:

$hashdata{level1}{level2}{level3} = 'store anything i want';

is there something that can easily do this? package?

thanks


Solution

  • A most well-known tool is probably Data::Diver

    use warnings;
    use strict;    
    use Data::Dump qw(dd);
    
    use Data::Diver qw(DiveVal);
    
    my @elems = qw(lev1 lev2 lev3);
    
    my %hash;
    
    DiveVal(\%hash, @elems) = "value";
    
    dd \%hash;
    

    The DiveVal is an lvalue subroutine (can be assigned to), and which autovivifies when it can.