首页 > 解决方案 > 更新一个或多个数组的哈希值

问题描述

我正在初始化一个哈希表,如下所示:-

my %AllCountStats = ();
foreach my $Log (@LogList) {
    foreach my $Func (keys %AllFuncNames) {
        push @{$AllCountStats{$Log}}, {Func=>$Func,Count=>0};
    }
}
print Dumper (\%AllCountStats);

Dumper 输出如下所示:-

$VAR1 = {
    'log.1' => [
        {
            'Count' => 0,
            'Func' => 'Function A'
        },
        {
            'Func' => 'Function B',
            'Count' => 0
        },
    }
    'log.2' => [
        {
            'Count' => 0,
            'Func' => 'Function A'
        },
        {
            'Count' => 0,
            'Func' => 'Function X'
        },
    };

现在我需要遍历散列数组的散列,并通过手术更新每个 Func 的 Count 值。使用上面的例子,我应该发出什么命令来将 log.1 的 Func=Function A 值更新为新的值(即不是 0)?这是我尝试在何处/如何进行更新的示例...

foreach $Log (@LogList) {
    foreach (sort {$a->{SCmdLineNum} <=> $b->{SCmdLineNum}} @{$SweepStats{$Log}}) {
        $SCmd = $_->{SCmd};
        my $inner = $AllCountStats{$Log}{$SCmd}{Count};
        $inner->{$_}++ for keys %$inner;
    }
}

但它不起作用。当 $inner 有效地变为 $AllCountStats{log.1}{Function B}{Count} 时,我怎样才能干净地更新它的 Count 值?

标签: perlhashmap

解决方案


$AllCountStats{$Log}是对数组的引用,但您将其视为对哈希的引用。

这个

$AllCountStats{$Log}{$SCmd}{Count}

应该

$AllCountStats{$Log}[$i]{Count}

目前还不清楚你想要什么价值$i。我们会回到那个。


接下来,以下是没有意义的:

my $inner = $AllCountStats{$Log}[$i]{Count};
$inner->{$_}++ for keys %$inner;

$inner只是一个数字,而不是哈希引用。你要

my $inner = $AllCountStats{$Log}[$i]
++$inner->{Count};

要不就

++$AllCountStats{$Log}[$i]{Count};

回到$i。我最好的猜测是你想增加值等于Count的记录的。Function$SCmd

for my $log_name (@LogList) {
   my $log = $AllCountStats{$log_name};

   for my $stats_rec (@{$SweepStats{$Log}}) {  # Useless sort removed.
      my $SCmd = $stats_rec->{SCmd};
      for my $log_rec (@$log) {
         ++$log_rec->{Count} if $log_rec->{Function} eq $SCmd;
      }
   }
}

如果是这样的话,如果你构建它会更简单%AllCountStats,看起来像

my %AllCountStats = (
   'log.1' => {
       'Function A' => 0,
       'Function B' => 0,
   },
   ...
);

那么,你所需要的就是

for my $log_name (@LogList) {
   my $log = $AllCountStats{$log_name};
   for my $stats_rec (@{$SweepStats{$Log}}) {
      ++$log->{ $stats_rec->{SCmd} };
   }
}

推荐阅读