in reply to sort sub in a different package

Next time, turn on strict and warnings.
use strict; use warnings; package joe; my @names = ('joe', 'aaron'); package FP; sub sortNames ($$) { my ($x, $y) = @_; print "$x vs $y\n"; return $x cmp $y; } package joe; my @sorted = sort {FP::sortNames($a,$b)} @names; print "sorted : @sorted\n";

Replies are listed 'Best First'.
Re^2: sort sub in a different package
by bart (Canon) on Apr 21, 2005 at 15:17 UTC
    Now, if you read the docs on sort, you can see that you don't have to handcraft this mode, as it is built into perl:
    If the subroutine's prototype is ($$), the elements to be compared are passed by reference in @_, as for a normal subroutine. This is slower than unprototyped subroutines, where the elements to be compared are passed into the subroutine as the package global variables $a and $b (see example below). Note that in the latter case, it is usually counter-productive to declare $a and $b as lexicals.
    What a surprise, you did use a prototype. So this will work:
    my @names = qw(Brad Aaron Joseph); package FP; sub sortNames ($$) { my ($x, $y) = @_; print "$x vs $y\n"; return $x cmp $y; } package joe; my @sorted = sort FP::sortNames @names;

    Note that the sub must already be compiled, or the prototype for the sub must otherwise already be known, when this sort statement is parsed.

    Update Much to my surprise, the latter doesn't seem to be true. It works just as well, with the FP::sortNames sub defined after the sort call. Can anyone explain?

      I found nothing about that in the sort documentation, like you I imagine. I only guess that this check for the prototype is done at run-time instead of compile time, as the following modification may suggest:
      #!/usr/bin/perl -w use strict; package joe; my @names = ('joe', 'aaron'); package FP; sub sortNames ($$) { print "$_[ 0 ] vs $_[ 1 ]\n"; return $_[ 0 ] cmp $_[ 1 ]; } package joe; my @sorted = sort nonexistent @names; print "sorted : @sorted\n"; CHECK {print "here I am\n"} __END__ here I am Undefined subroutine in sort at asort.pl line 15.

      Flavio (perl -e 'print(scalar(reverse("\nti.xittelop\@oivalf")))')

      Don't fool yourself.
Re^2: sort sub in a different package
by BrowserUk (Patriarch) on Apr 21, 2005 at 15:11 UTC

    Or more simply,

    #!/usr/footprints_perl/bin/perl -w use strict; package joe; my @names = ('joe', 'aaron'); package FP; sub sortNames ($$) { print "$_[ 0 ] vs $_[ 1 ]\n"; return $_[ 0 ] cmp $_[ 1 ]; } package joe; my @sorted = sort FP::sortNames @names; print "sorted : @sorted\n"; __END__ P:\test>junk joe vs aaron sorted : aaron joe

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco.
    Rule 1 has a caveat! -- Who broke the cabal?