user690182
user690182

Reputation: 279

perl: how to map an array to a nested hash

Given a hash:

my %stats_info = (
  "2010-10-31T23:30:00",
  [
    ["ASBG_#_Mp_at_bsNo-25_#_sbgMpNoOfSessionSetupAttempts",3290387,],
    ["ASBG_#_Mp_at_bsNo-25_#_sbgMpNoOfMediaStreams", 508],
    ["BSBG_#_Mp_at_bsNo-35_#_sbgMpNoOfSessionSetupAttempts",3289764,],
    ["BSBG_#_Mp_at_bsNo-35_#_sbgMpNoOfMediaStreams", 496],
    ["ASBG_#_Mp_at_bsNo-35_#_sbgMpNoOfSessionSetupAttempts",3289764,],
    ["ASBG_#_Mp_at_bsNo-35_#_sbgMpNoOfMediaStreams", 496],
    ["BSBG_#_Mp_at_bsNo-25_#_sbgMpNoOfSessionSetupAttempts",3290387,],
    ["BSBG_#_Mp_at_bsNo-25_#_sbgMpNoOfMediaStreams", 508],
  ],
  "2010-10-31T23:15:00",
  [
    ["ASBG_#_Mp_at_bsNo-25_#_sbgMpNoOfSessionSetupAttempts",3288736,],
    ["ASBG_#_Mp_at_bsNo-25_#_sbgMpNoOfMediaStreams", 610],
    ["ASBG_#_Mp_at_bsNo-35_#_sbgMpNoOfSessionSetupAttempts",3288113,],
    ["ASBG_#_Mp_at_bsNo-35_#_sbgMpNoOfMediaStreams", 619],
    ["BSBG_#_Mp_at_bsNo-35_#_sbgMpNoOfSessionSetupAttempts",3288113,],
    ["BSBG_#_Mp_at_bsNo-35_#_sbgMpNoOfMediaStreams", 619],
    ["BSBG_#_Mp_at_bsNo-25_#_sbgMpNoOfSessionSetupAttempts",3288736,],
    ["BSBG_#_Mp_at_bsNo-25_#_sbgMpNoOfMediaStreams", 610],
  ],
  "2010-10-31T23:45:00",
  [
    ["BSBG_#_Mp_at_bsNo-25_#_sbgMpNoOfSessionSetupAttempts",3291863,],
    ["BSBG_#_Mp_at_bsNo-25_#_sbgMpNoOfMediaStreams", 445],
    ["ASBG_#_Mp_at_bsNo-35_#_sbgMpNoOfSessionSetupAttempts",3291239,],
    ["ASBG_#_Mp_at_bsNo-35_#_sbgMpNoOfMediaStreams", 449],
    ["ASBG_#_Mp_at_bsNo-25_#_sbgMpNoOfSessionSetupAttempts",3291863,],
    ["ASBG_#_Mp_at_bsNo-25_#_sbgMpNoOfMediaStreams", 445],
    ["BSBG_#_Mp_at_bsNo-35_#_sbgMpNoOfSessionSetupAttempts",3291239,],
    ["BSBG_#_Mp_at_bsNo-35_#_sbgMpNoOfMediaStreams", 449],
  ],
) ;

and a sorted array of the keys :

my @timeline = ("2010-10-31T23:15:00", "2010-10-31T23:30:00", "2010-10-31T23:45:00",) ;

and a helpful answer to a similar question

My QUESTION is:

Here is how I can access the original hash:

foreach my $t (@timeline)   
{ 
    my $i=0 ; 
    while( exists($stats_info{$t}[$i]) )    
    { 
        # counter: $stats_info{$t}[$i][0] , quantify: $stats_info{$t}[$i][1] ; 
        $i = $i+1 ; 
    } 
}

At the moment the case is that the pair (counter, quantify) is an array and I would like to make this pair counter=>quantify (a hash) inside $stats_info{$t}

Upvotes: 0

Views: 1165

Answers (1)

jwodder
jwodder

Reputation: 57660

for my $key (@timeline) {
 my %newhash = ();
 for my $pair (@{$stats_info{$key}}) {
  my($k, $v) = @$pair;
  $newhash{$k} = $v;
 }
 $stats_info{$key} = { %newhash };
}

or even:

for my $key (keys %stats_info) {
 $stats_info{$key} = { map { @$_ } @{$stats_info{$key}} };
}

Upvotes: 4

Related Questions