【发布时间】:2012-04-30 07:08:06
【问题描述】:
下面的程序应该取一个数组并对其进行压缩,这样就没有重复的乘积并将总数相加,所以:
A B B C D A E F
100 30 50 60 100 50 20 90
变成:
A 150
B 80
C 60
D 100
E 20
F 90
下面的代码按照我想要的方式运行和工作:
#! C:\strawberry\perl\bin
use strict;
use warnings;
my @firstarray = qw(A B B C D A E F);
my @secondarray = qw (100 30 50 60 100 50 20 90);
my @totalarray;
my %cleanarray;
my $i;
# creates the 2d array which holds variables retrieved from a file
@totalarray = ([@firstarray],[@secondarray]);
my $count = $#{$totalarray[0]};
# prints the array for error checking
for ($i = 0; $i <= $count; $i++) {
print "\n $i) $totalarray[0][$i]\t $totalarray[1][$i]\n";
}
# fills a hash with products (key) and their related totals (value)
for ($i = 0; $i <= $count; $i++) {
$cleanarray{ $totalarray[0][$i] } = $cleanarray{$totalarray[0][$i]} + $totalarray[1][$i];
}
# prints the hash
my $x = 1;
while (my( $k, $v )= each %cleanarray) {
print "$x) Product: $k Cost: $cleanarray{$k} \n";
$x++;
}
但是在打印哈希之前,它给了我六次“使用未初始化的值加法 (+)”错误。对 Perl 非常陌生(这是我在教科书之外的第一个 Perl 程序),有人能告诉我吗我为什么会这样?好像我已经初始化了所有东西......
【问题讨论】:
-
你从来没有初始化过
@cleanarray...错误信息告诉你确切地是什么问题。 -
这段代码应该已经因错误
Global symbol "%cleanarray" requires explicit package name at ...而死掉。因此,您发布实际使用的代码的可能性很小。 -
@TLP - 你是对的,我发布了
@cleanarray,在我的代码中是%cleanarray,已编辑。
标签: perl