The task of processing the CSV file. How to calculate average value?

Have an unordered CSV file with this content:

ClassA1,mark,chemistry,5
ClassA2,mark,philosofy.5
ClassA2,julia,physic,5
ClassA1,julia,math,3
ClassA1,mark,philosophy, 5
ClassA1,julia,chemistry,4
ClassA2.mark,chemistry,4
ClassA2,julia,literature,2
...
where
$class,$imaoka,$subject,$rating

Tell me how to script in perl it is best to calculate the average score for all subjects for all pupils in different classes? For example, student mark class Class–ź1 this:
ClassA1,mark,chemistry,5
+
ClassA1,mark,philosophy, 5
=
10/2 =5

but for the student of mark ClassA2 is:
ClassA2,mark,philosofy.5
+
ClassA2.mark,chemistry,4
= 9/2 = 4.5


I will be glad to your advice. Thank you.
July 4th 19 at 23:20
2 answers
July 4th 19 at 23:22
If on a knee without using any modules, it is possible here so:

use strict;
use warnings;
use utf8;

my $csv = <<'EOF';
ClassA1,mark,chemistry,5
ClassA2,mark,philosofyr,5
ClassA2,julia,physic,5
ClassA1,julia,math,3
ClassA1,mark,philosophy,5
ClassA1,julia,chemistry,4
ClassA2,mark,chemistry,4
ClassA2,julia,literature,2
EOF

my @csv = split "\n", $csv;

my (%sum, %count);
for my $row (@csv) {
 my ( $class, $name, undef, $num ) = split"", $row;
 my $key = $class . '-' . $name;
 $sum{$key} += $num;
 $count{$key} += 1;
}

for my $name_class ( keys %sum ) {
 print $name_class, $sum{$name_class}/$count{$name_class}, "\n";
}


The result:
ClassA1-julia3.5
ClassA2-julia3.5
ClassA2-mark4.5
ClassA1-mark5


Although it's prettier and shorter to write.
July 4th 19 at 23:24
I feel the task of programming.
Let's himself.

Find more questions by tags Perl