gryphon has asked for the wisdom of the Perl Monks concerning the following question:
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;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Inconsistent column Schwartzian Transform attempt
by dragonchild (Archbishop) on Mar 15, 2002 at 21:03 UTC | |
|
Re: Inconsistent column Schwartzian Transform attempt
by abstracts (Hermit) on Mar 15, 2002 at 21:01 UTC | |
|
Re: Inconsistent column Schwartzian Transform attempt
by RMGir (Prior) on Mar 15, 2002 at 21:01 UTC | |
by RMGir (Prior) on Mar 16, 2002 at 16:36 UTC | |
by Juerd (Abbot) on Mar 16, 2002 at 18:17 UTC | |
by RMGir (Prior) on Mar 16, 2002 at 19:41 UTC | |
by I0 (Priest) on Mar 16, 2002 at 18:46 UTC |