perl:如何将数组映射到嵌套哈希

时间:2011-07-13 18:59:43

标签: arrays perl hash map

给出哈希:

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],
  ],
) ;

和键的排序数组:

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

similar question

的有用答案

我的问题是:

  • 如何使“BSBG _#_ Mp_at_bsNo-35 _#_ sbgMpNoOfMediaStreams”成为“449”的关键?

以下是我可以访问原始哈希的方法:

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 ; 
    } 
}

目前的情况是该对(计数器,量化)是一个数组,我想在$ stats_info {$ t}内建立这个对counter => quanty(哈希)

1 个答案:

答案 0 :(得分:4)

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

甚至:

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