Frequently, when processing rows returned by a DB query, we need to group sets of rows. We often want to display a single header for the group and/or calculate some aggregate values. Here is an abstract example.
@a = (['a',1],['a',2],['b',3],['b',4]); # "db read"
my $old;
my $total = 0; # init
foreach my $row (@a) {
if ($old && $old ne $row->[0]) {
print "$old: $total\n"; # finish row block
$total = 0; # init
}
$total += $row->[1]; # processrow block
$old = $row->[0]; # check variable
}
print "$old: $total\n"; # finish row block
Bad things:
- the first finish appears in a non-intuitive place -- at the very beginning of the loop!
- init and finish sections are repeated! In the real code, these sections are both a dozen lines, and they constantly get out-of-sync: a major source of bugs.
- needing to keep track of the $old (last group) is annoying.
- This gets very messy if there are nested groups, e.g. if you want to total by group and by subgroup.
But, I'd like not to:
- have to iterate through the array with a counter variable
Anyone developed a clean solution for this? Any advice would be appreciated.
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.