Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

$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

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
[Discipulus]: Tux did you already read Bluetooth people presence detector :)?

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (5)
As of 2018-05-24 06:58 GMT
Find Nodes?
    Voting Booth?