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

Hi,
We can sort an array using sort command.
For example
@array = sort {$a <=> $b} @array;
Suppose if I use $c and $d, instead of $a and $b, it's not working. So there should some speciality with this $a,$b variable.
Please, anyone can tell me regarding this?
Thank you,

Replies are listed 'Best First'.
Re: sorting technique
by chb (Deacon) on Feb 18, 2005 at 09:55 UTC
    $a and $b are indeed special variables in a sort-block. See perldoc -f sort and perldoc perlvar.
      Thanks a lot.
Re: sorting technique
by gopalr (Priest) on Feb 18, 2005 at 10:07 UTC

    Hi,

    $c and $d are not special package variables in sort function.

    The sort function takes an optional code block, which lets you replace the default alphabetic comparison subroutine with your own. This comparison function is called each time sort has to compare two values. The values to compare are loaded into the special package variables $a and $b.

Re: sorting technique
by samy_kumar (Scribe) on Feb 18, 2005 at 11:57 UTC
    Have alook at this link for more info.
Re: sorting technique
by Anonymous Monk on Feb 21, 2005 at 12:01 UTC
    Yes, $a and $b are special, as mentioned. Think about it, suppose sort would not use special variables, and you could pick any variable you wanted. How would sort than distinguish between:
    sort {$a <=> $b}
    and
    sort {$b <=> $a}
    Or what if you have something like:
    sort {$a < $c ? $b <=> $d : $a <=> $e}
    then what?
    A reply falls below the community's threshold of quality. You may see it by logging in.