Hi,
I've got a problem to average lines which have same name.
For exemple:
Strawberries 10 15 14 20
Pineapples 14 17 2 18
Apples 4 12 24 18
Strawberries 20 12 13 24
I would like to average values by fruit name. So, for pineapples, that easy, it's the average of the line. For strawberries, the average must be on the first and the last lines in this exemple.
I think about array, hash and referencing but that doesn't work. Something like create a hash with fruit name in key and a link towards an array containing values, in value of the hash.
Thanks for help!
Here is my code:
open (fruit_file, $file);
#-----------------------------
#Array and hash creation
#-----------------------------
while (my $line = <fruit_file>){
if ($line =~/(\d+)\s/g){ #to recover values
$val=$1;
}
if ($line =~/([a-zA-Z])/g){ #to recover fruit names
$fruit=$1;
if( !$rh_fruit -> {$fruit}){ #if the rh_fruit hash is empty
$rh_fruit -> {$fruit}={[]}; #create an array
}
push @{$rh_fruit -> {$fruit} , $val}; #fill the array with values
}
}
close fruit_file;
#----------------------------
#Values acces
#----------------------------
open (RESULT, ">".$result);
foreach $val(@{$rh_fruit -> {$fruit}}){
#if ($val ne "NA"){
$sum += $val;
$nbval++;
#}
$moy = $sum/$nbval;
print RESULT $fruit."\t".$moy."\n";
}
close RESULT;