perl - How to build up a hash data structure -


i having trouble figuring out how create several %th2 structures (see below) each of values of $th1{0}, $th1{1}, , on.

i trying figure out how traverse keys in second hash %th2. running error discussed in so,

can't use string ("1") hash ref while "strict refs" in use

also, when assign %th2 each key in %th1, assuming copied %th1 anonymous hash, , not overriting values re-use %th2.

use strict;  %th1 = (); %th2 = (); $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;  $key1 (keys %th1) {     print $key1."\n\n";     $key2 (keys %$key1)     {       print $key2->{"status"};     }      #performing $key2 won't work. strict ref error. } 

change:

$th1{$idx} = %th2; 

to:

$th1{$idx} = \%th2; 

then can create loop as:

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

or.. more explicitly:

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

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -