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

Re: Summing repeated counts for items stored in separate file

by wind (Priest)
on Jul 27, 2007 at 22:42 UTC ( [id://629216]=note: print w/replies, xml ) Need Help??


in reply to Summing repeated counts for items stored in separate file

Put the data into a single hash structure, and then do the math for your formatting at the very end. Throw in a couple of warnings in case the file processing ends prematurely.

Use List::Util for quick functions to manipulate a list of values.
use List::Util qw(sum max min); use strict; my $keysfile = 'keys.txt'; my $valsfile = 'vals.txt'; open(KEYS, $keysfile) or die "Can't open $keysfile: $!"; open(VALS, $valsfile) or die "Can't open $valsfile: $!"; my %data; while (!eof(KEYS) && !eof(VALS)) { chomp(my $key = <KEYS>); chomp(my $val = <VALS>); push @{$data{$key}}, $val; } warn "Premature end of $keysfile\n" if !eof(VALS); warn "Premature end of $valsfile\n" if !eof(KEYS); foreach my $name (sort keys %data) { my $values = $data{$name}; my $count = @$values; my $total = sum(@$values); my $average = $total / $count; my $max = max(@$values); my $min = min(@$values); print "$name => total=$total, average=$average, max=$max, min=$min +\n"; }
- Miller

Replies are listed 'Best First'.
Re^2: Summing repeated counts for items stored in separate file
by dmorgo (Pilgrim) on Jul 27, 2007 at 23:22 UTC
    Thanks, that is a very nice solution. I didn't think of the idea of storing lists under each key then processing them afterward, and didn't know about the eof test.

    And pretty code too.

    Thanks again.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-03-28 10:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found