Wow, I feel like the ultimate necroposter here.

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 - Tcl's dictionary sort doesn't seem to do this, and will place 1.2 above 1.02 in the sort.

So I extended your example to check for the string length of the compared numbers if they match numerically - If they match numerically, but have differing string lengths, then one must have leading zeroes. I also implemented the code into a subroutine:

sub dict_sort { my @unsorted = @_; my @sorted = map $_->[0], sort { my $i = 0; { my $A = $a->[1][$i]; my $B = $b->[1][$i]; defined($A) || defined($B) # Stop if both undef and ( defined($A) <=> defined($B) # Defined wins over undef or ( $A !~ /\d/ || $B !~ /\d/ # $A or $B is non-integer ? (lc $A cmp lc $B) # ?? Stringy lowercase || ( $A cmp $B) # -> Tie breaker : $A <=> $B # :: $A and $B are integers or ( length($A) <=> length($B) # If numeric comparison ret +urns the same, check length to sort by leading zeroes ) ) or ++$i && redo # tie => next part ); } } map [ $_, [ split /(\d+)/ ] ], @unsorted; return @sorted; }

I'm not sure that this thread will ever get any more posts, but hopefully this helps somebody out!


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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.