octopusgrabbus
octopusgrabbus

Reputation: 10685

How to build up a hash data structure

I am having trouble figuring out how to create several %th2 structures (see below) each of which will be the values of $th1{0}, $th1{1}, and so on.

I am also trying to figure out how to traverse the keys in the second hash %th2. I am running into that error that is discussed frequently in SO,

Can't use string ("1") as a HASH ref while "strict refs" in use

Also, when I assign %th2 to each key in %th1, I am assuming this is copied into %th1 as an anonymous hash, and that I am not overriting those values as I re-use %th2.

use strict;

my %th1 = ();
my %th2 = ();
my $idx = 0;

$th2{"suffix"} = "A";
$th2{"status"} = 0;
$th2{"consumption"} = 42;

$th1{$idx} = %th2;

$idx++;

$th2{"suffix"} = "B";
$th2{"status"} = 0;
$th2{"consumption"} = 105;

$th1{$idx} = \%th2;

for my $key1 (keys %th1)
{
    print $key1."\n\n";
    for my $key2 (keys %$key1)
    {
      print $key2->{"status"};
    }

    #performing another for my $key2 won't work. I get the strict ref error.
}

Upvotes: 2

Views: 90

Answers (2)

ikegami
ikegami

Reputation: 385506

  1. $th1{$idx} = %th2;
    

    should be

    $th1{$idx} = \%th2;
    

    Only scalars can be stored in a hash, so you want to store a reference to %th2. (%th2 in scalar context returns a weird string containing info about the hash's internals.)

  2. keys %$key1
    

    should be

    keys %{ $th1{$key1} }
    

    $key1 is a string, not a reference to a hash.

  3. $key2->{"status"}
    

    should be

    $th1{$key1}{$key2}{"status"}
    

    $key2 is a string, not a reference to a hash.

Upvotes: 1

PP.
PP.

Reputation: 10864

Change:

$th1{$idx} = %th2;

to:

$th1{$idx} = \%th2;

Then you can create your loop as:

for my $key1 (keys %th1) {
    for my $key2 (keys %{$th1{$key1}} ) {
        print( "Key1=$key1, Key2=$key2, value=" . $th1{$key1}->{$key2} . "\n" );
    }
}

Or.. more explicitly:

for my $key1 (keys %th1) {
    my $inner_hash_ref = $th1{$key1};

    for my $key2 (keys %{$inner_hash_ref}) {
        print( "Key1=$key1, Key2=$key2, value=" . $inner_hash_ref->{$key2} . "\n" );
    }
}

Upvotes: 4

Related Questions