in reply to Why do we need $a and $b to be special?

By default, $a and $b will be with us forever (in perl5) for backward compatibility; however, since 5.6.0, perl has supported having a named comparison routine with a $$ prototype to indicate that you want the elements to sort passed as parameters instead of as $a and $b:
$ perl -we'sub evenfirst ($$) { ($_[0]&1) <=> ($_[1]&1) or $_[0] <=> $ +_[1] } print sort evenfirst 0..9' 0246813579

Replies are listed 'Best First'.
Re^2: Why do we need $a and $b to be special?
by rinceWind (Monsignor) on Aug 01, 2004 at 09:29 UTC
    ... however, since 5.6.0, perl has supported having a named comparison routine with a $$ prototype to indicate that you want the elements to sort passed as parameters instead of as $a and $b
    I didn't know that. How would the $$ prototype be seen in a CODE ref? Would it still work?

    I tend to avoid prototypes normally, as they don't do what you expect, and seem to be more trouble than they are worth.

    --
    I'm Not Just Another Perl Hacker

      I didn't know that. How would the $$ prototype be seen in a CODE ref? Would it still work?

      Just apply the prototype to the coderef, for example:

      my $sort = sub ($$) { $_[0] cmp $_[1] }; my @sorted = sort $sort @unsorted;
      Agree with you re: prototypes. I don't think you can do it with a code block specified after "sort", you actually have to declare a sub. (However, in general you can attach prototypes to coderefs by putting the prototype between "sub" and the code block.)

      I think this was implemented because without it you can't very well use a sort subroutine from another package, since it will be looking at that package's $a and $b, while sort will be setting the current package's $a and $b.