1

下面的程序应该采用一个数组并对其进行压缩,以便没有重复的产品并将总数相加,因此:

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 程序),有人可以告诉我为什么正在发生吗?好像我已经初始化了一切......

4

3 回答 3

3

它在这些行中给了我编译错误:

my @cleanarray;

这是一个哈希。

my %cleanarray;

和这里:

$cleanarray{ $totalarray[0][$i] } = $cleanarray{$totalarray[0][$i]} + totalarray[1][$i];

你错过了 的印记totalarray。这是$totalarray[1][$i]

因为$cleanarray{$totalarray[0][$i]}不存在未定义的消息。使用较短的:

$cleanarray{ $totalarray[0][$i] } += totalarray[1][$i];

将在没有警告的情况下工作。

于 2012-04-29T18:19:29.107 回答
0

您正在使用 cleanarray 作为哈希,但它被声明为数组

于 2012-04-29T18:18:04.287 回答
0

您可能会发现您更喜欢这种程序重组。

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); 

# prints the data for error checking
for my $i (0 .. $#firstarray) {
  printf "%d) %s %.2f\n", $i, $firstarray[$i], $secondarray[$i];
}
print "\n";

# fills a hash with products (key) and their related totals (value)
my %cleanarray; 
for my $i (0 .. $#firstarray) {
  $cleanarray{ $firstarray[$i] } += $secondarray[$i];
}

# prints the hash
my $n = 1;
for my $key (sort keys %cleanarray) {
  printf "%d) Product: %s Cost: %.2f\n", $n++, $key, $cleanarray{$key};
}
于 2012-04-29T23:08:06.380 回答