I have to agree that the spaceship operator is special ! But the sequence of sorting is still a very mysterious thing to me. I could imagine sorting is just like a factory conveyancy belt, pushing the elements thru some sorting machine. To find out what's exactly going on, I've decided to take a peep into the spaceship and this is what I got which I still do not understand precisely how it sorts. I would appreciate very much if someone could offer an explanation on the undermentioned results.
Thanks ! @a = qw ( 12 34 14 0 35 44 2); @b = sort spaceship @a; print join ',', @b; sub spaceship { print "\$a = $a whilst \$b = $b\n"; $a<=>$b; }; Results :- $a = 14 whilst $b = 0 $a = 0 whilst $b = 35 $a = 14 whilst $b = 35 $a = 34 whilst $b = 14 $a = 14 whilst $b = 44 $a = 14 whilst $b = 2 $a = 12 whilst $b = 14 $a = 44 whilst $b = 35 $a = 34 whilst $b = 44 $a = 34 whilst $b = 35 $a = 2 whilst $b = 12 $a = 0 whilst $b = 12 $a = 0 whilst $b = 2 0,2,12,14,34,35,44 ----- Original Message ----- From: "Jonathan E. Paton" <[EMAIL PROTECTED]> To: <[EMAIL PROTECTED]>; <[EMAIL PROTECTED]> Sent: Sunday, November 11, 2001 6:21 PM Subject: Re: explanation needed on sort using {$a<=>$b} > > @a= qw (68 3 5 67 54 23 69 ); > > > > @b = sort {-1} @a; ### what happens here ! > > results = 5,3,68,67,69,23,54 > > > > Hey look, its reversed the order of the numbers either side > of the number 67! Extremely useful :P You shouldn't use > this sort, since it breaks for other quantities of numbers. > > > @c = sort {$a <=> $b} @a; ### what happens here ! > > results = 3,5,23,54,67,68,69 > > Sorts numerically. > > > I know that sort by default sort in ascii order, I > > wanted to know what exactly happens to the "spaceship" > > operator. Could somebody help me to visualize what's > > taking place. > > > > Thanks > > Sort needs a subroutine which returns -1, 0, 1 as the > result of comparing two elements. The values mean (where > $a and $b is a pair of values from the array): > > -1 = put $a before $b > 0 = doesn't matter which way to put $a and $b (i.e equal) > 1 = put $a after $b > > Now, the lovely <=> operator returns the following: > > -1 - when $a is less than $b > 0 - when $a is equal to $b > 1 = when $a is greater than $b > > Combine these: > > When $a is less than $b put $a first. > When $a is same as $b leave alone. > When $a is greater than $b put $a second. > > Result: > > You have a numerical sort! You don't really need to know > the impliementation of the sort (I was going to explain it, > but my explaination seemed too hazy). > > Jonathan Paton > _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]