【发布时间】:2012-11-15 12:58:44
【问题描述】:
我有一个解析 Excel 文件并执行以下操作的 Perl 脚本:它计算 A 列中的每个值、B 列中的元素数,脚本如下所示:
use strict;
use warnings;
use Spreadsheet::XLSX;
use Data::Dumper;
use List::Util qw( sum );
my $col1 = 0;
my %hash;
my $excel = Spreadsheet::XLSX->new('inout_chartdata_ronald.xlsx');
my $sheet = ${ $excel->{Worksheet} }[0];
$sheet->{MaxRow} ||= $sheet->{MinRow};
my $count = 0;
# Iterate through each row
foreach my $row ( $sheet->{MinRow}+1 .. $sheet->{MaxRow} ) {
# The cell in column 1
my $cell = $sheet->{Cells}[$row][$col1];
if ($cell) {
# The adjacent cell in column 2
my $adjacentCell = $sheet->{Cells}[$row][ $col1 + 1 ];
# Use a hash of hashes
$hash{ $cell->{Val} }{ $adjacentCell->{Val} }++;
}
}
print "\n", Dumper \%hash;
输出如下所示:
$VAR1 = {
'13' => {
'klm' => 1,
'hij' => 2,
'lkm' => 4,
},
'12' => {
'abc' => 2,
'efg' => 2
}
};
这很好用,我的问题是:如何访问此输出 $VAR1 的元素以便执行:对于值 13,klm + hij = 3 并获得这样的最终输出:
$VAR1 = {
'13' => {
'somename' => 3,
'lkm' => 4,
},
'12' => {
'abc' => 2,
'efg' => 2
}
};
所以基本上我想要做的是循环遍历我的最终哈希值,并根据唯一键访问其特定元素,最后计算它们的总和。
任何帮助将不胜感激。 谢谢
【问题讨论】:
-
你想用什么键来计算总和?所有的钥匙?指定的键子集?
-
是的,这个总和会影响所有的键,13 将有 klm + hij,12 也将有 klm + hij。我举的例子很糟糕,对不起。在更现实的情况下,我会有: $VAR1 = { '13' => { 'somename' => 3, 'lkm' => 4, }, '12' => { 'somename' => 9, 'lkm' => 6 } };