No need to get real fancy here.

#!/usr/bin/perl -w use strict; my @a = ("1-1-2", "6-1-2", "3-1-4", "1-1-1"); @a = sort{ my ($A_chapter,$A_sub_chapter,$A_verse) = split(/[-]/,$a); my ($B_chapter,$B_sub_chapter,$B_verse) = split(/[-]/,$b); $A_chapter <=> $B_chapter or $A_sub_chapter <=> $B_sub_chapter or $A_verse <=> $B_verse }@a; print "@a"; __END__ prints: 1-1-1 1-1-2 3-1-4 6-1-2
The "Schwartzian Transform" is far less important that it used to be due to recent(since ver 5.8) sorting performance improvements. In any event, this appears to be a "how to do it?" question rather than a "how to do it faster?" question.

updated with better variable names in the sort. Names and code formatting do matter.

Yet another comment: The idea behind the "Schwartzian Transform" is to calculate all this stuff like in the split's in one single pass thru the data and then use the resulting values for comparison in the sort. That idea being that we've saved all this calculation on a per pair comparison basis. The idea of the "Guttman-Rosler Transform" is to make a single string value that can be compared with a string comparison (cmp). I don't think that the OP needs either one.

If you have a choice in formatting data like the OP's case, one way is to choose to add leading zeroes so that the normal cmp sort order "works out", this is the "Guttman-Rosler Transform" without any transformation! ie. @array = sort @array; works.

If the set to be sorted is relatively small, the only thing that really matters is how clear the sort is. I think the above is very clear about what it does.


In reply to Re: Custom sort with string of numbers by Marshall
in thread Custom sort with string of numbers by linuxfan

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.