How could I optimize ...
Note that johngg's approach of Re^3: sort in array of hash required is not an 'optimization' in the sense of execution speed; I doubt it would run significantly, if at all, faster.
However, it offers, IMHO, potential significant advantages in terms of maintainability. E.g., the group of keys keynum keyname name can be factored out (if you could get rid of that pesky '#' that's buzzing around in there) into an array definition (possibly made a constant) and used in many places without concern for having 'forgotten something'. If it becomes necessary to change anything about this group of keys, it is only necessary to do so in one place.