RedRaven
RedRaven

Reputation: 735

Why does this Perl script give me a "Use of uninitialized value in addition (+)" error

The program below should take an array and compress it so that there are no repeated products and add up the totals, so:

A B B C D A E F
100 30 50 60 100 50 20 90

Becomes:

A 150
B 80
C 60
D 100
E 20
F 90

The code below runs and works the way I want it to:

#! 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++;
}

However before printing the hash it gives me the "Use of uninitialized value in addition (+)" error" six times. Being very new to Perl (this is my first Perl program outside of a text book), can someone tell me why this is happening? It seems like I have initialized everything...

Upvotes: 1

Views: 5420

Answers (3)

Borodin
Borodin

Reputation: 126722

You may find you prefer this reorganization of your program.

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

Upvotes: 0

Birei
Birei

Reputation: 36262

It gives me compile errors in these lines:

my @cleanarray;

It is a hash.

my %cleanarray;

And here:

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

You missed the sigil of totalarray. It is $totalarray[1][$i]

The undefined message it is because $cleanarray{$totalarray[0][$i]} doesn't exists. Using the shorter:

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

will work without warnings.

Upvotes: 3

MK.
MK.

Reputation: 34527

You are using cleanarray as a hash but it is declared as an array

Upvotes: 0

Related Questions