perlreferencehashmap

Can't figure out multi-dimensional Perl hash references: Not a HASH reference


Yes, I've looked through many of the "not a HASH reference" articles, but none seem to address my issue. I have a multidimensional hash. Inside a for-loop where I'm a few levels down in my hash just working with the values of the last hash in the chain, I wanted to save typing by making a hash reference to this last hash.

This value exists:

$date2solveInfo{ $weekDate }{ $dow }{ secs } = 2272;

I assign my hash reference like so:

my $ref = \( %date2solveInfo{ $weekDate}->{ $dow});

The debugger is about to execute that line as shown below.


  DB<2> x %date2solveInfo  # showing what we're taking a reference to

0  '2020-09-07'
1  HASH(0x7faaec193f68)
   'Tue' => HASH(0x7faaec193f20)
      'secs' => 2272

  DB<3> s    # does the reference assignment above

  DB<3> x $ref  # showing the contents of $ref

0  REF(0x7faaea208ef8)
   -> HASH(0x7faaec193f20)
         'secs' => 2272

  DB<4> p $ref->{"secs"}  # try to deref the hash reference

Not a HASH reference at (eval 15)[/System/Library/Perl/5.30/perl5db.pl:738] line 2, <$fh> line 10.

It seems like the debugger is showing $ref is a reference to hash, so I'm puzzled.


Solution

  • $ref is not a hash reference (like { secs => 2272 }), but a reference to a hash reference (like \{ secs => 2272 }. Hence one need to dereference it again:

      DB<5> p ${$ref}->{"secs"}
    2272
    

    To access a simple hash reference you would have to use

    my $ref = $date2solveInfo{ $weekDate}->{ $dow};
    

    Instead you've added another layer of reference by using

     # replacing `%` with `$` in `date2solveInfo`, as warnings suggest one should do
     my $ref = \( $date2solveInfo{ $weekDate}->{ $dow});