After a good night's sleep and some thought I did come up with a way to do what I wanted using a single for loop. The reason that I had to keep working on it, depsite tilly's code is that the output wasn't quite what I needed...
To define the issue a little better -- I am outputting tables, and for the sake of rendering speed, it would be faster to output only a single row for each group with a single cell containing all the users who belong to that group. tilly's second snippet, while clean, can only (at least, as far as I can figure it) easily output a row per user... although I could simply output the group name once by testing against the old_id to see when I'd moved into a new group.
Here's what the output should look like in pseudo HTML:
<cell><table> <row> <cell>Group 1 name <cell>Email 1, Email 2, Email 3, Email 4... <row> <cell>Group 2 name <cell>Email 5, Email 6, Email 7... </table>
The reason I wanted to avoid the hash-based solution was that my data is already ordered by the SQL query I'm doing, so it seems strange to stuff ordered information into an 'unordered' hash only to have to sort it again.
So, here's what I finally came up with:
print <<EOTableHeaders; <table border="1" cellpadding="3" cellspacing="4"> <tr> <td class="list"><b class="list">Group Name</b></td> <td class="list"><b class="list">Group Members</b></td> <td class="list"><b class="list">Edit Mail Group</b></td> </tr> EOTableHeaders for (my $i = 0, my $j = 0; $i < (scalar(@{$all_groups}) - 1); $i++, $j +++) { print "<tr"; if ($j % 2 == 0) { print qq|bgcolor="#AAAACC"|; } print ">\n"; print qq|<td valign="top"><span class="list">| . $all_groups->[$i] +[1] |</span></td>\n|; print qq|<td valign="top"><span class="list">|; while ((defined($all_groups->[($i + 1)][0])) && ($all_groups-> +[$i][0] == $all_groups->[($i + 1)][0])) { print $all_groups->[$i][2] . "<br>"; $i++; } print $all_groups->[$i][2]; print "</td>\n"; print qq|<td><a href="edit_group.html?group_id=| . $all_groups->[$ +i][0] . |&&group_name=| . Apache::Util::escape_uri($all_groups->[$i][ +1]) |>Edit this Email Group</a></td>\n|; print "</tr>"; } </tr> </table>
Or, for a slightly cleaner version:
for (my $i = 0; $i < (scalar(@{$all_groups}) - 1); $i++) { print "Group name: " . $all_groups->[$i][1] . "\n"; while ((defined($all_groups->[($i + 1)][0])) && ($all_groups->[$i] +[0] == $all_groups->[($i + 1)][0])) { print "\tEmail: " . $all_groups->[$i][2] . "\n"; $i++; } print "\tEmail: " $all_groups->[$i][2] . "\n"; }
In reply to Re: Re (tilly) 1: Nested For Loop giving me extra iterations
by jreades
in thread Nested For Loop giving me extra iterations
by jreades
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |