【问题标题】:Why does this Perl script give me a "Use of uninitialized value in addition (+)" error为什么这个 Perl 脚本给我一个“使用未初始化的附加值 (+)”错误
【发布时间】: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 ...错误信息告诉你确切地是什么问题。
  • 我敢说你可能想看看perldsc 甚至perlstyle。拥有干净的数据结构并适当地访问它可以避免很多问题。
  • 这段代码应该已经因错误Global symbol "%cleanarray" requires explicit package name at ... 而死掉。因此,您发布实际使用的代码的可能性很小。
  • @TLP - 你是对的,我发布了@cleanarray,在我的代码中是%cleanarray,已编辑。

标签: perl


【解决方案1】:

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

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

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

【讨论】:

  • 完美,成功了。再次,第一个编译器错误是我无法使用 Stackoverflow。谢谢。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 2011-03-12
      • 2014-02-05
      • 1970-01-01
      • 2018-01-13
      相关资源
      最近更新 更多