# How to Sort on a substr - PERL Beginners

Hi, I need to do a sort on a couple of column ranges. I want to be able to do a primary sort, on say, columns 21-25 and then a secondary sort on columns 40-49. Any ideas on how to approach this? TIA /j __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions./new_mail...

1. ## How to Sort on a substr

Hi,

I need to do a sort on a couple of column ranges.

I want to be able to do a primary sort, on say, columns 21-25 and
then a secondary sort on columns 40-49.

Any ideas on how to approach this?

TIA

/j

__________________________________
Do you Yahoo!?
Yahoo! Mail - You care about security. So do we.
http://promotions./new_mail
Jeff Guest

2. ## Re: How to Sort on a substr

Jeff Westman wrote:

Yes.

1. Check out the docs for the sort() function.

2. Check the Perl FAQ:

perldoc -q "How do I sort an array by (anything)?"

--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
Gunnar Guest

3. ## Re: How to Sort on a substr

Jeff Westman wrote:

Can you get away with concatenating the 2 substrings? That would cut
down your sort to pass. Either way you'll have to define a sort
function I think.

Rob Guest

4. ## Re: How to Sort on a substr

On Thursday 15 July 2004 13:54, Jeff Westman wrote:

Hello,

This should work:

my sorted = map substr( \$_, 15 ),
sort
map substr( \$_, 20, 5 ) . substr( \$_, 39, 10 ) . \$_,
unsorted;

John
--
use Perl;
program
fulfillment

John Guest

5. ## RE: How to Sort on a substr

Jeff Westman wrote:

Assuming you're numbering columns from 1:

rows = sort { substr(\$a, 20, 5) cmp substr(\$b, 20, 5)
|| substr(\$a, 49, 10) cmp substr(\$b, 49, 10) } rows;

If you're numbering columns from 0, adjust the offsets above.

The general concept for multi key sorting is to combine the comparisons with
a logical "or" operation.

John Krahn gave you a sort of modified "Schwartzian Transform" (did I spell
that right?) approach which is faster if you have a large number of rows to
process, but a bit less clear...
Bob Guest

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•