Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

$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'
instead?

Thank you

Comment on $a <=> $b
Re: $a <=> $b
by roboticus (Canon) 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 (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 (Cardinal) 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2014-12-25 18:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (161 votes), past polls