http://www.perlmonks.org?node_id=1054381


in reply to Selecting successive lines

If I were going to do this and wanted to have it expandable, I'd probably plan to make a hash like this (you can simplify it if you don't care about keeping track of student IDs and never have students with the same names):
my %records = ( 12445 => { name => 'Jack', scores => [ 45, 10 ], }, 234254 => { name => 'Jill', scores => [ 45, 10 ], }, );

If the data are consistently in the format shown, the following will make the hash (it can accept scores w/ decimals). It then calculates and reports the mean score.

#!/usr/bin/env perl use strict; use warnings; use feature 'say'; use List::Util 'sum'; my %records; while ( my $name = <DATA> ) { my ($id) = <DATA> =~ /(\d+)$/; my ($score) = <DATA> =~ /(\d+\.?\d*)$/; <DATA>; chomp( $name, $id, $score ); $records{$id}{name} = $name; push @{ $records{$id}{scores} }, $score; } for ( sort { $a <=> $b } keys %records ) { my $name = $records{$_}{name}; my @scores = @{ $records{$_}{scores} }; my $mean = sum(@scores) / @scores; say "$name ($_) has an average score of $mean"; } __DATA__ Jack Student ID - 12445 Math Score - 45 Jill Student ID - 234254 Math Score - 90 Jack Student ID -12445 Math Score2 - 33 Jill Student ID - 234254 Math Score2 - 10

OUTPUT:

Jack (12445) has an average score of 39 Jill (234254) has an average score of 50