1833875 Members
2029 Online
110063 Solutions
New Discussion

Why doesn't sort work?

 
SOLVED
Go to solution
John Wolfe_1
Advisor

Why doesn't sort work?

Hello,

I'm trying my hand at perl and I have a problem. I have an array with the values
100.9, 10.3, 12, 50, -38
I do this:
@array2 = sort @array1;

Instead of coming out in correct order, array2 prints out like this:
-38, 10.3, 100.9, 12, 50

What is wrong with perl's sort?

Thanks, John W.
At least I have a job.
1 REPLY 1
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Why doesn't sort work?

Hi John:

The simple answer is that sort is doing just what you are telling it to do. In the absense of a comparison routine, sort sorts in lexical order but you obviously want numeric order. The cure is quite simple: supply a comparison subroutine. In this case, we can use the inline method via the 'spaceship' operator.

@array2 = sort {$a <=> $b} @array1;

In the case, < 0 is returned if a < b; 0 if a = b; and > 0 is a > b. You can reverse the order of the sort by using {$b <=> $a}.

This should fix you, Clay
If it ain't broke, I can fix that.