下面的程序应该采用一个数组并对其进行压缩,以便没有重复的产品并将总数相加,因此:
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 程序),有人可以告诉我为什么正在发生吗?好像我已经初始化了一切......