-1

I have a file with a list of lines like

at 12345 injected value 1 to 'signal_A'
at 12345 injected value 0 to 'signal_B'
at 12346 injected value 1 to 'signal_A'
at 12348 injected value 1 to 'signal_A'
at 12350 injected value 0 to 'signal_A'
at 12354 injected value 0 to 'signal_A'

From this file, I want to read till the end of the file and I want to build a hash of hashes something like

%tab = (
       12345 => {           
       signal => "signal_A",           
       value  => "1",        
     },

      12345 => {
       signal => "signal_B",
       value  => "1",
     },
);

Also I want to iterate this hash table.

Will highly appreciate your help.

giri_lp
  • 9
  • 1

1 Answers1

4

You have two elements with the same key. That data structure cannot exist. How about the following instead:

%tab = (
   12345 => [
      {
         signal => "signal_A",           
         value  => "1",        
      },

      {
         signal => "signal_B",
         value  => "1",
      },
   ],
   12346 => [
      {
         signal => "signal_A",           
         value  => "1",        
      },
   ],
   ...
);

You'd use the following to created it

push @{ $tab{$id} }, { signal => $signal, value => $value };

You can iterate over the structure using

for my $id (keys %tab) {
   for $event (@{ $tab{$id} }) {
      ...$event->{signal}...;
      ...$event->{value}...;
   }
}
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Hi ikegami, Sorry about the typo, that exactly fits my need :) Can you please tell me how can I print the hash table? – giri_lp Nov 23 '12 at 09:45
  • Good catch about double key. Seems toplevel hash must be replaced with array since 12345 is a pid/timestamp/line number – Galimov Albert Nov 23 '12 at 10:04
  • Hi , I tried this and worked as well. foreach $key (sort keys %tab) { my $tsig = $tab{$key}{Sig}; my $tval = $tab{$key}{Val}; print "The val at $key $tsig, $tval \n"; } – giri_lp Nov 23 '12 at 10:06