![]() |
|
Perl-Sensitive Sunglasses | |
PerlMonks |
Re: Sorting numerials first and then numerials with alpha characters lastby johngg (Canon) |
on Oct 29, 2021 at 15:45 UTC ( #11138218=note: print w/replies, xml ) | Need Help?? |
An alternative to the Schwartzian Transform shown by hippo is the Guttman Rosler Transform where the sort keys are pulled from the text and then keys and text are formed into a single string that can be sorted alphanumerically. Once sorted the original text can be extracted from the end of the string. The string can be formed using something like sprintf or pack, which I use here. In the first map the regular expression captures one or more digits in $1 then zero or more letters in $2; note that no error checking for bad lines is done here. Then $2 is checked to see if there were letters, an indicator of their presence (1) or not (0) being the first sort key, pack'ed as an unsigned char in 1 byte using the "c" template; the second key is the numerical value packed in big-endian order (which sorts correctly) and the third is the letters, if present, packed with NULL padding to the right. Finally the original text is tacked on the end, also NULL padded. Then the string is sort'ed and the original line is unpack'ed in the second map, using the "x" template to skip over the keys and the "a" template to strip off any NULL padding. This code:-
Produces this output.
I hope this is of interest. Update: Expanded wording about the primary sort key. Cheers, JohnGG
In Section
Seekers of Perl Wisdom
|
|