http://www.perlmonks.org?node_id=951783


in reply to Re^2: Dictionary-style sort a la Tcl?
in thread Dictionary-style sort a la Tcl?

I stumbled across this solution, and found it fell over when it met the likes of the following: qw{ 1.01 1.3 1.02 1.2 };

$A <=> $B does a numerical comparison, but strips any leading zeroes from the number, so how 1.02 and 1.2 are sorted will depend on their original order in the list

No, the spaceship operator  <=> does no stripping of any kind, it does a numerical comparison, and numbers don't have leading zeros , 0002 is 02 is 2

The problem is with the code/regex, which turns decimals into an array of integers , and then does a numerical comparison on each portion -- not gonna work

I'm not too familiar with Tcl's sort order, but what works for me (esp for mp3s) is to lowercase the string, and pad all digits with zeroes (sometimes 6, sometimes 20)

#!/usr/bin/perl -- use strict; use warnings; my @list = ( qw{ bigBoy bigbang bigboy x10y x9y x11y 1.01 1.3 1.02 1.2 x1.1y x1.01y x2.3y x2.1y } ); print join "\n", map { $$_[0] } sort { $$a[1] cmp $$b[1] } map { my $f = $_; $f =~ s/(\d+)/sprintf '%06d',$1/ge; [ $_, lc $f ] } @list; __END__ 1.01 1.02 1.2 1.3 bigbang bigBoy bigboy x1.1y x1.01y x2.1y x2.3y x9y x10y x11y

Replies are listed 'Best First'.
Re^4: Dictionary-style sort a la Tcl?
by Anonymous Monk on Feb 16, 2012 at 14:43 UTC
    Sorry, I guess I could have worded that better - it doesn't 'strip' leading zeroes, it just ignores them as it's doing a numerical comparison. In any case, the change I added seems to make the sort identical to the Tcl dictionary sort. I'm not sure about yours.