Search code examples
perlreferencehashmapdereference

Unknown Hash of Hashes of Hashes


i can fetch data from a Database with the following perl code:

my %hash = $vars->getVarHash;   #load data into a hash
print Dumper(\%hash);

The output of the Dumper looks like this:

$VAR1 = {
          'HASH(0x55948e0b06b0)' => undef
        };

Now i know that this hash points to a hash of variables, and each of them points to a list of options for each variable (i guess a "hash of hashes"), sth like this:

HASH(0x55948e0b06b0) --> Variable_a --> Option_a_1, Option_a_2 ...
                     --> Variable_b --> Option_b_1, Option_b_2 ...
                     --> Variable_c --> ...

How do i correctly dereference this hash so i can get the values of the Variables and each of is Options?


Solution

  • The basic problem is that you can only dereference references. A hash is not a reference, so "dereference a hash" doesn't make sense.

    Your dumper output,

    $VAR1 = {
              'HASH(0x55948e0b06b0)' => undef
            };
    

    doesn't show a nested data structure or reference or anything. It's literally a one-element hash whose (single) key is the string "HASH(0x55948e0b06b0)" and whose value is undef. There's nothing you can do with this structure.

    What probably happened is that getVarHash returns a reference to a hash (a single value), which (by assigning to a hash) you've implicitly converted to a key whose corresponding value is undef. Hash keys are always strings, so the original reference value was lost.

    Perl can tell you about this particular problem. You should always start your Perl files with

    use strict;
    use warnings;
    

    The warning for this particular mistake is

    Reference found where even-sized list expected at foo.pl line 123.
    

    The solution is to store the returned reference in a scalar variable:

    my $hash = $vars->getVarHash;
    print Dumper($hash);
    

    Then you can use all the usual methods (as described in e.g. perldoc perlreftut) to dereference it and access its contents, such as keys %$hash, $hash->{$key}, etc.