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…
It gives me compile errors in these lines:
It is a hash.
And here:
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:will work without warnings.