Search code examples
perlperl-data-structures

How should I store values in a multi-level Perl hash?


I am looking to do something like this. I remember I had some issues with values disappearing when programming like this. Is this type of structure "correct/valid" for a hash?

my %VAR;
$VAR{SCALAR} = "test scalar";
$VAR{ARRAY}[0] = "test array";
$VAR{HASH}{NAME}[0] = "test hash array 1";
$VAR{HASH}{NAME}[1] = "test hash array 2";
$VAR{HASH}{NAME}[2]{SOMEHASH} = "test hash array hash 1";
$VAR{HASH}{NAME}[2]{ANOTHERHASH} = "test hash array hash 2";

Solution

  • I see no reason why this wouldn't work. What issues are you seeing?

    If you want to make sure your data structure looks like what you'd expect, I recommend something like Data::Dumper:

     # set up your %VAR hash as you like
     use Data::Dumper;
     print Dumper(\%VAR);
    

    Should get something like:

    $VAR1 = {
          'HASH' => {
                      'NAME' => [
                                  'test hash array 1',
                                  'test hash array 2',
                                  {
                                    'ANOTHERHASH' => 'test hash array hash 2',
                                    'SOMEHASH' => 'test hash array hash 1'
                                  }
                                ]
                    },
          'ARRAY' => [
                       'test array'
                     ],
          'SCALAR' => 'test scalar'
        };