Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Selecting successive lines

by frozenwithjoy (Curate)
on Sep 17, 2013 at 03:52 UTC ( #1054381=note: print w/ replies, xml ) Need Help??


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


Comment on Re: Selecting successive lines
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1054381]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2015-07-31 06:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (274 votes), past polls