in reply to Cleaner build of an AoH for nested loop?

I might write it this way.

foreach my $case ( @{$all_cases} ) { if ( $case_list && $case->{examiner} eq $case_list->[-1]->{examiner} ) { push @{ $case_list->[-1]->{casedata} }, $case; } else { push @{$case_list}, { examiner => $case->{examiner}, casedata => [$case] }; } }

That eliminates all the extra variables, and you're not looping over indices instead of elements, but it seems a little longer (even though it's really fewer statements).

Replies are listed 'Best First'.
Re^2: Cleaner build of an AoH for nested loop?
by bradcathey (Prior) on Mar 06, 2009 at 13:53 UTC

    This was the eloquence I was looking for kyle, though the -1 list counters looked odd at first. But my original counters and looping just didn't feel "best practices."

    Thanks.

    —Brad
    "The important work of moving the world forward does not wait to be done by perfect men." George Eliot

      If the -1 index bothers you, you can build the list backwards. In the else clause, unshift instead of push, then you can use refer to the front of the list with [0] instead of the end with [-1]. Then when it's done, use reverse to get the original order. Given that, you have to decide if you want to have to take the extra step to reverse the list, or live with the odd look of [-1].

      foreach my $case ( @{$all_cases} ) { if ( $case_list && $case->{examiner} eq $case_list->[0]->{examiner} ) { push @{ $case_list->[0]->{casedata} }, $case; } else { unshift @{$case_list}, { examiner => $case->{examiner}, casedata => [$case] }; } } @{$case_list} = reverse @{$case_list};