The "fix" again would be to break the process down into two steps. First, find all the links, and put the references into a hash of reference by category.
Then, sort the hash by category, (sort key) and pull each link reference out, THEN send it to link.html along with a number, and add that to the $OUTPUT variable one at a time.
What is being done now, is the link is being taken from the databse, turned into an HTML nugget, then put into a hash by category, which is then flattened into the larger output variable by adding each "category" of links as a chunk.
You have to break that into discreete steps, in order to number the output, and add the links to $OUTPUT one at a time.
http://www.postcards.com
FAQ: http://www.postcards.com/FAQ/LinkSQL/