Search code examples
perlhashhash-of-hashes

how to increment hash of hash in perl


failing to properly populate a HoH using this code: when i run the loop using below:

while (my $form = $form_rs->next ()){
    my $menu=$form->get_column("fmenu");
    my $script=$form->get_column("fscript");
    my $name=$form->get_column("ftitle");

    $itemList->{$menu} = {
        $script => $name
    };
}
print Dumper $itemList;

it runs correctly but since $menu is repeating it only keeps last value in the HoH. So i get erroneous output in Data Dumper. I get only 1 record for each 'menu', whereas there should be many.

getting:

itemList=>{
    menu1=>{
        script1=>formName1
    },
    menu2=>{
        script3=>formName3
    }
    ...(and so on)
}

whereas EXPECTED:

itemList=>{
    menu1=>{
        script1=>formName1,
        script2=>formName2
    },
    menu2=>{
        script3=>formName3,
        ...(and so on)
    }
    ...(and so on)
}

pl help. thank you.


Solution

  • Then you want to update $itemList->{$menu}{$script} rather than assign a reference to a one-element hash to $itemList->{$menu}.

    $itemList->{$menu}{$script} = $name;