truthseeker66 has asked for the wisdom of the Perl Monks concerning the following question:

I see a line, "@sorted = sort {$a <=> $b} @array;"

The text book I read says, "When you need to sort data in
numerical order, you have to add an argument to the sort
statement. What confuses me is '$a <=> $b'.
Could you explain what this line do? Can I use '$c <=> $d'
instead?

Thank you

Replies are listed 'Best First'.
Re: $a <=> $b
by roboticus (Chancellor) on Oct 09, 2012 at 18:18 UTC

    truthseeker66:

    Inside the body of the sort block, $a and $b refer to the items being compared. If you use $c and $d, sort isn't going to do what you want it to do.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: $a <=> $b
by tobyink (Canon) on Oct 09, 2012 at 18:57 UTC

    roboticus' answer is correct. The documentation for the special variables $a and $b is in perlvar.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: $a <=> $b
by GrandFather (Saint) on Oct 10, 2012 at 01:31 UTC

    roboticus answered the immediate question, but note that this is why you should avoid using $a and $b a general purpose variables: they are magical and should really only be used inside sort.

    Note too that using sort without a {...} bit is like sort {$a cmp $b}. That is, sort's default is to do a string sort.

    True laziness is hard work