in reply to A new golf challenge - Natural Sorting
It is small (97 strokes, including the meaningful newline), but it is also very fast. There are certainly places where a few characters can be shaved but several of those break subtle features such as one demonstrated in the example code: sorting the sample data correctly even when each record ends with a newline.
use strict; use warnings; sub naturalSort { my$i;s/(\d+)/pack"aNa*",0,length$1,$1/ge,$_.=$".$i++for # 345678 1 2345678 2 2345678 3 2345678 4 2345678 5 2345 my@x=map{lc}@_;@_[map{(split)[-1]}sort@x] #8 6 2345678 7 2345678 8 2345678 9 234567 } my @data= <DATA>; chomp @data if $\; print for naturalSort(@data); __END__ amsTerdam40 amstelveen 1 AmstErdam5 Amsterdam amsterDamed A
Run it normally or with "perl -l ..." to see that it sorts the same with or without the newlines in the strings being sorted.
- tye
|
|---|