Greetings all,

I had an interesting problem come up recently, and I thought, "This would be a great opportunity to really sit down and mentally absorb the coolness of the Schwartzian Transform." What I need to do is take a series of strings that can be split into columns and sort them based on each column. The problem is that the "columns" from each string will not be consistent.

What I've come up with thus far seems to work with all the test cases I've thrown against it. However, I have some serious concerns about certain parts, and I'm also a little worried about efficiency.

#!/usr/bin/perl -w use strict; my @unordered = ( '12 Corinthians 5:10', 'Hebrews 11:15', '1 Corinthians 13:23', '2 Corinthians 1:3', 'John 3:16', '1 Corinthians 12:10', '1 Corinthians 2:10', '1 Corinthians 2:10' ); my @ordered = map { $_->[0] } sort { for (my $x=1; $x<$#{$a}+1; $x++) { if (($a->[$x] =~ /\D/) || ($b->[$x] =~ /\D/)) { my $compare = $a->[$x] cmp $b->[$x]; return $compare if ($compare != 0); } else { my $compare = $a->[$x] <=> $b->[$x]; return $compare if ($compare != 0); } } return 0; } map { [ $_, split(/[ :]/) ] } @unordered; print join "\n", @ordered; exit;

One worry is with the upper limit to $x in the for loop. It only deals with $a. Then there's the inside of the for loop. I have this feeling that it's totally not efficient. Is there a nifty way to run the dual compare types without having to build the if? I added the $compare step so as to avoid having to run the compare twice in each case, but is there a better way? Ultimately, I'd like this to work with strings like "X 2 4 S w r y" where case may be important as well.

-gryphon
code('Perl') || die;


In reply to Inconsistent column Schwartzian Transform attempt by gryphon

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.