I think the problem is mostly due to how you're storing the results as you fetch them from the database. If you use a hash keyed on incident.id and push the results for each action in, then the data will already be in the format you want to print it in. Here's an example:
#!/usr/local/bin/perl
use strict;
use warnings;
my @query = (
{ i_id => 1, summary => 's 1', a_id => 1, description => 'a 1', },
{ i_id => 1, summary => 's 1', a_id => 2, description => 'a 2', },
{ i_id => 1, summary => 's 1', a_id => 3, description => 'a 3', },
{ i_id => 2, summary => 's 2', a_id => 4, description => 'a 4', },
{ i_id => 2, summary => 's 2', a_id => 5, description => 'a 5', },
);
my %results;
# analagous to your while ( my $href = $sth->fetchrow_hashref() ){
while( my $href = shift @query ){
# treat each entry in %results as a hash ref
unless( $results{ $href->{ i_id } } ){
# save the summary information in the summary key
$results{ $href->{ i_id } }->{ summary } = $href->{ summary };
}
# push a hash ref of action information into { actions }
push @{ $results{ $href->{ i_id } }->{ actions } },
{ a_id => $href->{ a_id },
desc => $href->{ description },
};
}
# now it's grouped by incident, and you can print it:
foreach my $i_id ( keys %results ){
print "Incident: $i_id - $results{ $i_id }->{ summary }\n";
foreach my $action ( @{ $results{ $i_id }->{ actions } } ){
print " $action->{ a_id }: $action->{ desc }\n";
}
}
note that the last foreach, where the printing happens, is pretty straightforward - loop over the keys (one for each incident), print the incident info, and then loop through the actions for each. The output looks like this:
Incident: 1 - s 1
1: a 1
2: a 2
3: a 3
Incident: 2 - s 2
4: a 4
5: a 5