Yes,
kevbot's solution with a hash is good. Here is what I typed while
keybot was also typing - this preserves the numbers in each row if more calculations are needed. If there are only 30 rows, a hash of array is a good idea. If there are 100,000 rows, that advice would change. Here the hash gets rid of the need to deal with
index[0] of the array of array (2-D array). A more efficient way can be done by processing row by row and outputting a line result when the first number changes.
#!usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %HoA; # a Hash of Array
while (my $line = <DATA>)
{
my ($bucket, $num) = $line =~ m/^\s*(\d+)\s*\|\s*(\d+)/;
push @{$HoA{$bucket}},$num;
}
my $total;
foreach my $key (sort {$a<=>$b} keys %HoA)
{
my $line_total;
foreach my $num (@{$HoA{$key}})
{
$line_total += $num;
}
print "Line $key total = $line_total\n";
$total += $line_total;
}
print "Grand Total = $total\n";
=Prints
Line 1 total = 150
Line 2 total = 75
Line 3 total = 55
Grand Total = 280
=cut
__DATA__
1|10
1|20
1|30
1|40
1|50
2|15
2|25
2|35
3|1
3|2
3|3
3|4
3|5
3|6
3|7
3|8
3|9
3|10
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.