为什么这个Perl脚本给我一个“使用未初始化的值(+)”错误

时间:2012-04-29 18:07:54

标签: perl

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

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程序),有人可以告诉我为什么会这样?看来我已经初步化了所有事情......

3 个答案:

答案 0 :(得分: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];

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

答案 1 :(得分:0)

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

答案 2 :(得分: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};
}
相关问题