in reply to Problem with Schwartzian Transform nested in another sort from a different package

This is one of the very few good uses for prototypes that I know of. (I forget who pointed this one out to me, but it was on perlmonks.)

Just have your sort functions declared with a prototype of ($$) and it will pass data in through @_ and never use $a or $b. (Avoiding confusion about what package $a and $b are to be found in.) That is write:

sub mycmp ($$) { my ($first, $second) = @_; return 1 if $first ne ( mysort($first, $second) ); return -1 if $first eq ( mysort($second, $first) ); return 0; } # and elsewhere ... sort {&Whatever::Package::mycmp} map ... # or put in in a variable my $cmp = \&Whatever::Package::mycmp; ... sort $cmp map ... # of if you don't mind a speed hit and don't trust the user my $cmp = sub ($$) {Whatever::Package::mycmp(@_)}; ... sort $cmp map ...
(Should work in 5.6 on up.)

Incidentally coding a cmp function in terms of a sort function strikes me as both obscure and inefficient.

  • Comment on Re: Problem with Schwartzian Transform nested in another sort from a different package
  • Download Code

Replies are listed 'Best First'.
Re: Re: Problem with Schwartzian Transform nested in another sort from a different package
by ronald (Beadle) on Apr 15, 2004 at 23:15 UTC
    Thanks for the tip on prototypes.

    Yes, this approach is obscure and inefficient. When the OO interface I put on the module (not mine) ended up failing, it's what I found, and I got to wondering...

    Once I've mastered this topic, I'll probably implement a different approach altogether.