in reply to How to loop over groups
I always wanted a good solution to this myself. I've done it that way more times than I'd like to admit. Adding a look-ahead removes a lot of awkwardness of processing near the top of the loop and redundant code for the last record.
Another advantage of this partial solution is you have the complete next record so you can easily check for changes in other fields.
YuckFoo
@a = (['a',1],['a',2],['b',3],['b',4]); $last = ['', '']; for $i (0..$#a) { $this = $a[$i]; $next = defined $a[$i+1] ? $a[$i+1] : $last; $total += $this->[1]; if ($this->[0] ne $next->[0]) { print "$this->[0]: $total\n"; $total = 0; } }
|
|---|