It happens to produce the correct sort in this case because of the narrow data set used.

Actually it doesn't produce a correct sort, its very close, but not correct. But it does match your sort exactly :)

In any case, I find having more than one cmp confusing, so I usually just pad zeros where appropriate, like

#~ @sorted = map { $_->[0] } @sorted = map { sprintf '%-20s %s', @$_ } sort { $b->[1] cmp $a->[1] } map { my $f = $_; no warnings 'uninitialized'; my( @didots ) = split /[.]/, ( /-([.\d]+)/ )[0]; my $ret = sprintf( '%01d.%01d.%01d ', @didots); ## %03d%03d%03d should be sufficiently futureproof if(my( $digits ) = /ID(\d+)-/ ){ $ret = "1 $ret".sprintf( '%03d ', $digits ) } else { $ret = "0 $ret"; } [ $f, $ret ]; } @unsorted; print Dumper( \@sorted ); __END__ $VAR1 = [ 'ID15-ABC-6.1 1 6.1.0 015 ', 'ID3-ABC-6.1 1 6.1.0 003 ', 'ID12-ABC-5.1.5 1 5.1.5 012 ', 'ID5-ABC-5.1.5 1 5.1.5 005 ', 'ID12-ABC-5.1 1 5.1.0 012 ', 'ID9-ABC-5.1 1 5.1.0 009 ', 'ID5-ABC-5.1 1 5.1.0 005 ', 'ABC-6.1 0 6.1.0 ', 'ABC-5.1.5 0 5.1.5 ', 'ABC-5.1 0 5.1.0 ' ];

Usually pad to 3 digits is sufficient, but sometimes I need to go to 20


In reply to Re^4: Sorting array by Anonymous Monk
in thread Sorting array by fdegir

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.