Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

$a <=> $b

by truthseeker66 (Novice)
on Oct 09, 2012 at 18:13 UTC ( #998048=perlquestion: print w/ replies, xml ) Need Help??
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'

Thank you

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


    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.


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

Re: $a <=> $b
by tobyink (Abbot) 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 (Sage) 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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://998048]
Approved by philipbailey
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2015-11-27 11:53 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (727 votes), past polls