Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

$a <=> $b

by truthseeker66 (Novice)
on Oct 09, 2012 at 18:13 UTC ( [id://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

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-03-29 12:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found