in reply to Creating Flags

I would organize the program around the organization of data you need to achieve. Learning to do this takes practice and also learning from the examples of others.

You need to group your data according to the name in each record. Hashes are good for grouping data. I would first build a hash, keyed by name, containing an array of all the records for each name. It would be convenient to split the record into fields at this stage, pretty much as you are doing, so this will result in a hash (keyed by name) of arrays (records) of arrays (fields). The difference from your current approach is that you have an array of all the records and a hash of arrays containing only the ordinals. I would merge these into one hash or arrays of arrays.

Having grouped the data, I would then sort it, modify the ordinals and print the results. You already have a loop that iterates over the keys of a hash, so you know how to do that. You can easily sort the keys if you need to by using sort keys %hash instead of just keys %hash.

Each hash element is a reference to an array. You are already working with array references in @DB, so you know how to do that. You need to sort this array according to the original ordinal, but remember that each array element is itself an array reference (a reference to the array of field values). But, again, you have already dealt with this situation in your subroutine by_weird_sort_order(), so you can probably see how to do this. Since the sort by name is already done (the outer loop iterating over the hash keys), you only need to sort by ordinal.

Once your array of records is sorted, you need to set the ordinals to 'S', 'M' or 'T'. I can think of several ways to do this and none of them are as simple as I would like. Probably the easiest is to save the sorted list (my @sorted = sort ...), then set the ordinal of all the records to 'M', then set the ordinal of the first to 'S' and that of the last to 'T', then output them all.

I probably haven't explained this very well, but I hope this gives you some ideas to progress with your program. You could incorporate the ideas of the last section into your existing program if you don't want to reorganize it as much as I would.