Hi Monks,
In a recent data munging challenge, I had to calculate the average score of each unique key with multiple scores and output a tab deilimited file with the unique key, number of occurrences and their average scores. The input file is similar to the one listed below with unique key on column1 and scores in column2.
-------inp.txt-------- 1 196 1 190 1 200 2 20 3 25 3 19 3 39 4 40 4 41 4 45
Below is the code that does this. My question is as follows:
1. Is there simpler solution to this task? Will there be a memory problem for this code if the input file contains close to 300,000 lines?

2. Is there a one liner that can achieve the same?
use strict; use warnings; my $in_file = 'inp.txt'; open (IN, $in_file)|| die "couldn't open the in_file\n"; my %r; while (<IN>) { chomp; my $line = $_; my @f = split(/\t/, $line); push(@{ $r{$f[0]} }, $f[1]); } close IN; my @scores =(); my $count; my $i; foreach my $key (sort keys %r) { #print "$key\t"; @scores = @{ $r{$key} }; $count = scalar @scores; #print "@scores[0..$count]\n"; my $sum = 0; #for($i=0; $i <=@scores; $i++) for $i (0..$count) { $sum += $scores[$i]; } my $avg = ($sum/$count); print "$key\t$count\t$avg\n"; }
-US

In reply to Data munging by umasuresh

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.