开发者

Perl read log with over all count

I am trying read a log file using Perl,

I have around 500 line, something like

timestamp, amount1, amount2, amount3
12334        20         0       0
12335        0         20       0
12335        0         20       20
12336        0         20       0
12336        0         20       20

I want output as

12334 20  0   0
12335  0  40  20
12336  0  40  20

how to get this sort开发者_StackOverflow社区 of output?


You can use hash to summarize data for each timestamp, something like this:

# skip header
my $header = <DATA>;

# read data into a hash
my %summary =();
while(<DATA>) {
    chomp;
    my ($timestamp, @amounts) = split;
    for my $i (0..$#amounts) {
        $summary{$timestamp} ||= [];
        $summary{$timestamp}[$i] += $amounts[$i];
    }
}

# print out the summary
for my $timestamp (sort { $a <=> $b } keys %summary) {
    print $timestamp,"  ",join("  ",@{ $summary{$timestamp} }),"\n";
}

__DATA__
timestamp, amount1, amount2, amount3
12334        20         0       0
12335        0         20       0
12335        0         20       20
12336        0         20       0
12336        0         20       20

Of course if your data are any more complex, you should use proper parser (like Text::xSV) to process data.


%myHash = ();

while (<>) {
   my ($ts,$a1,$a2,$a3) = split;
   # Put into hash by ts-value
   if (exists $myHash{$ts}) {
      $myHash{$ts}{amount1} = $myHash{$ts}{amount1} + $a1;
      $myHash{$ts}{amount2} = $myHash{$ts}{amount2} + $a2;
      $myHash{$ts}{amount3} = $myHash{$ts}{amount3} + $a3;
   }
   else {
      $myHash{$ts}{amount1} = $a1;
      $myHash{$ts}{amount2} = $a2;
      $myHash{$ts}{amount3} = $a3;
   }    
}

And then just go through the keys of the hash and print out

foreach (keys %myHash) {
   printf("%5d %3d %3d %3d\n", $_, $myHash{$_}{amount1}, $myHash{$_}{amount2}, $myHash{$_}{amount3});
}

or something like that ... I haven't run through it, but something like this, I believe is what you want?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜