perl - 更新一个或多个数组的哈希值
问题描述
我正在初始化一个哈希表,如下所示:-
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 值?
解决方案
$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} };
}
}
推荐阅读
- html - 关于样式化我的链接的问题,我需要什么 css 来获得想要的外观
- javascript - handleInputChange - React Redux 文件上传
- notepad++ - Notepad ++:如何删除多行中的所有内容,除了大写中的单词
- java - 如何使用 `if-else` 语句从下面的代码中进行复杂性分析?
- java - 无法启动嵌入式 Jetty 服务器
- javascript - 如何根据 id 更新处于反应状态的对象数组
- python - Django 脆表单集未显示客户端验证的错误
- javascript - 带有创建的 PNG 的传单叠加层
- mongodb - Mongodb:获取库存中产品的平均持续时间
- html - 通过使用 css 3d 转换和透视,我无法再与 Firefox 中的可点击元素交互,但它适用于 chrome/Safari