[EMAIL PROTECTED] (Vic Norton) wrote:
>How do you package a sorting subroutine for use with sort? That's
>what I don't understand.
>
>For example I have written a "naturalorder" subroutine to sort
>strings like the "natural order" system extension.
>
>The script
>
> my @before = ( 'e 213', 'e21a', 'e 0212' );
> my @after = sort naturalorder @before;
> print "@after\n";
[...]
>I assume that I am losing $a and $b when my subroutine resides in the
>external package VTN::Utilities, but I don't know what to do about
>it. Can someone tell me how write a packaged sorting subroutine so
>that it works with sort?
Hi Vic,
This is not one of the most attractive parts of Perl 5.004.
If the sorting subroutine resides in a different package, you'll have to
explicitly use the caller's package in the routine:
package Fooey;
*naturalorder = *Blurgh::naturalorder; # alias subroutine (not important)
my @after = sort naturalorder ( 'e 213', 'e21a', 'e 0212' );
print "after: @after\n";
package Blurgh;
sub naturalorder { $Fooey::a cmp $Fooey::b }
I know that's probably not what you wanted to hear. If you don't want
to hard-code the calling package's name (i.e., it might be called from
several different packages) then here's one option:
package Fooey;
*naturalorder = *Blurgh::naturalorder;
{
local $Blurgh::caller = __PACKAGE__;
my @after = sort naturalorder ( 'e 213', 'e21a', 'e 0212' );
print "after: @after\n";
}
package Blurgh;
sub naturalorder {
${$caller.'::a'} cmp ${$caller.'::b'};
}
You might benchmark that to see if it's fast enough for you.
------------------- -------------------
Ken Williams Last Bastion of Euclidity
[EMAIL PROTECTED] The Math Forum