perlhashperl-data-structuresdata-dumper

Issue accessing Hash in perl


I have a Hash of following structure in perl -

my %testHash = (
        KeyL1 => {
            KeyLL1 => {
                KeyLLL1 => [1,2],
                KeyLLL2 => [2,3],
            },
            KeyLL2 => {
                KeyLLL1 => [1,2],
                KeyLLL2 => [2,3],
            },
            KeyLL3 => {
                KeyLLL1 => [1,2],
                KeyLLL2 => [2,3],
            },            
        },
        KeyL2 => {
            KeyLL1 => {
                KeyLLL1 => [1,2],
                KeyLLL2 => [2,3],
            },
            KeyLL2 => {
                KeyLLL1 => [1,2],
                KeyLLL2 => [2,3],
            },
            KeyLL3 => {
                KeyLLL1 => [1,2],
                KeyLLL2 => [2,3],
            }, 
        },
        );

Now, when I am trying to access it the following way, I am getting 'undef' as a result

my %tempHash = $testHash{'KeyL1'};
print Data::Dumper::Dumper($tempHash{'KeyLL1'});
print Data::Dumper::Dumper($tempHash{'KeyLL1'}{'KeyLLL1'});

Result --

$VAR1 = undef; $VAR1 = undef;

Please point to me what am I doing wrong. I am pretty new to perl.


Solution

  • The value of $testHash{'KeyL1'} is a hashref, not a hash.

    Hashrefs are scalars. my %tempHash = is not expecting a scalar.

    You need to dereference it:

    my %tempHash = %{$testHash{'KeyL1'}};