http://qs1969.pair.com?node_id=11138218


in reply to Sorting numerials first and then numerials with alpha characters last

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:-

use strict; use warnings; open my $inFH, q{<}, \ <<__EOD__ or die $!; <t id=2bc>Only the...</t> <t id=1>Only the...</t> <t id=12>Only the...</t> <t id=21>Only the...</t> <t id=1>Only the...</t> <t id=1a>Only the...</t> <t id=2>Only the...</t> <t id=2>Only the...</t> <t id=2>Only the...</t> <t id=2>Only the...</t> <t id=3>Only the...</t> <t id=17d>Only the...</t> <t id=35>Only the...</t> <t id=31>Only the...</t> <t id=2b>Only the...</t> <t id=4>Only the...</t> <t id=42>Only the...</t> <t id=5>Only the...</t> <t id=51>Only the...</t> <t id=2ac>Only the...</t> <t id=52>Only the...</t> <t id=6>Only the...</t> <t id=7>Only the...</t> __EOD__ print for map { unpack q{x13a*}, $_ } sort map { m{(?x) (?<=id=) ( \d+ ) ( [a-z]* ) (?=>)} && pack q{cNa8a*}, ( length $2 ? 1 : 0 ), $1, $2, $_ } <$inFH>; close $inFH or die $!;

Produces this output.

<t id=1>Only the...</t> <t id=1>Only the...</t> <t id=2>Only the...</t> <t id=2>Only the...</t> <t id=2>Only the...</t> <t id=2>Only the...</t> <t id=3>Only the...</t> <t id=4>Only the...</t> <t id=5>Only the...</t> <t id=6>Only the...</t> <t id=7>Only the...</t> <t id=12>Only the...</t> <t id=21>Only the...</t> <t id=31>Only the...</t> <t id=35>Only the...</t> <t id=42>Only the...</t> <t id=51>Only the...</t> <t id=52>Only the...</t> <t id=1a>Only the...</t> <t id=2ac>Only the...</t> <t id=2b>Only the...</t> <t id=2bc>Only the...</t> <t id=17d>Only the...</t>

I hope this is of interest.

Update: Expanded wording about the primary sort key.

Cheers,

JohnGG