You probably need to take a slightly-different approach in building your data structure:
-
Initialize an empty array.
-
Use a regular expression to compress all occurrences of multiple blanks into a single blank.
-
split the string on blanks into a temporary array.
-
Loop through this array, and split each element in turn, based on commas.
For each element, push a hashref onto the array in step #1.
-
Now, you can sort that array (from #1), using a function that considers the hash-elements. The difference here is that there is only one array being sorted, and each element within that array is a hashref containing two keys.