You say you are having difficulty, but you don't say what the difficulty is very clearly, making it difficult to help.
Perhaps the following will give you some ideas. Otherwise, you might be a bit more specific about what the difficulty is.
#!C:/strawberry/perl/bin/perl.exe
#
# See http://rick.measham.id.au/pdf-api2/
#
use strict;
use warnings;
use Data::Dumper::Concise;
my @records;
while(my $record = <DATA>) {
push(@records, [ split(/\s+/, $record) ]);
}
report({
group_by => 0,
sum_columns => [ 2, 3 ],
records => \@records,
});
report({
group_by => 1,
sum_columns => [ 2, 3 ],
records => \@records,
});
report({
group_by => 2,
sum_columns => [ 3 ],
records => \@records,
});
exit(0);
sub report {
my ($args) = @_;
# sum columns by group
my %groups;
foreach my $record (@{$args->{records}}) {
my $group = $groups{$record->[$args->{group_by}]} //= {};
$group->{count}++;
foreach my $sum_column (@{$args->{sum_columns}}) {
$group->{sum}->{$sum_column} += $record->[$sum_column];
}
}
# produce output
print "example output: group by column $args->{group_by}, sum colu
+mns " .
join(', ', @{$args->{sum_columns}}) . "\n";
foreach my $group (sort keys %groups) {
print join(' ',
$group,
map {
(
$groups{$group}->{count},
$groups{$group}->{sum}->{$_}
)
} @{$args->{sum_columns}}
) . "\n";;
}
print "\n";
}
__DATA__
U1 ID1 100 280
U1 ID1 137 250
U2 ID2 150 375
U1 ID2 100 100
U3 ID1 100 600
U9 ID3 137 200
Which produces:
example output: group by column 0, sum columns 2, 3
U1 3 337 3 630
U2 1 150 1 375
U3 1 100 1 600
U9 1 137 1 200
example output: group by column 1, sum columns 2, 3
ID1 3 337 3 1130
ID2 2 250 2 475
ID3 1 137 1 200
example output: group by column 2, sum columns 3
100 3 980
137 2 450
150 1 375
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.