Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sorting numbers correctly 1

Status
Not open for further replies.

ibjdt

Programmer
Nov 25, 2002
63
i have a database with information from which i pull a temp file like:

Code:
c-1
c-2
c-3.....
c-10
c-11....

i am using perl to sort and display the temp file like:

Code:
@doclist = sort {
(split '::', $a, 12)[0] cmp
(split '::', $b, 12)[0]
||
(split '::', $a, 12)[1] cmp
(split '::', $b, 12)[1]
} @doclist;

but it returns

Code:
c-1
c-10
c-11
c-2
c-3....

how can i get it to sort in proper order??
does the 'c-' make a difference??
i tried <=> instead of cmp, but it didn't help.

thanks.
 
i found an answer:

instead of:

Code:
@doclist = sort {
(split '::', $a, 12)[0] cmp
(split '::', $b, 12)[0]
||
(split '::', $a, 12)[1] cmp
(split '::', $b, 12)[1]
} @doclist;

i use:

Code:
@doclist = sort {
(split '::', substr ($a, 2, 6), 12)[0] cmp
(split '::', substr ($b, 2, 6), 12)[0]
} @doclist;

this sorts the items using all data past the 2nd character

 
A Schwartzian transform is probably a better solution:

Code:
my @unsorted = qw(c-3 c-1 c-10 c-11 c-2); 
my @sorted = map  {$_->[0]}
             sort {$a->[2] <=> $b->[2]}
             map  {[$_,split/-/]} @unsorted;
print map {"$_\n"} @sorted;

this line builds an array of anonymous arrays for @unsorted:

map {[$_,split/-/]} @unsorted;

which looks like:

[c-3,c,3]
[c-1,c,1]
etc
etc

then the sort uses the last element of each anonymous array ($a->[2] and $b->[2]) to sort the data (3,1,2,10,etc)

and this line:

my @sorted = map {$_->[0]}

gets the first element of each now sorted anonymous array, which is c-1, c-2 etc etc, and puts it into @sorted.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top