At 2:22 PM -0500 1/26/01, Vic Norton wrote:
>How do you package a sorting subroutine for use with sort? That's 
>what I don't understand.

[snip]

>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.

The global variables $a and $b are temporarily set in the package 
where the sort routine was compiled. So, if your sort subroutine is 
defined in an external package, to access the sort variables you'll 
need to make $a and $b properly qualified over there.

I just scanned what Ken Williams posted, which was good. Here's 
another way to  correctly handle the package scoping. Use the 
caller() function in the subroutine definition in the external 
package:

#!perl -w
package Utils::Sort;

use strict;
use vars qw/@ISA @EXPORT @EXPORT_OK $VERSION/;

$VERSION='0.1';
@ISA    = qw{Exporter};
@EXPORT = qw{&case_order};
@EXPORT_OK = qw{};

sub case_order {
   my ($pkg) = caller;
   no strict 'refs';
   my $a = ${$pkg.'::a'};
   my $b = ${$pkg.'::b'};

   # OK, now we can sort...
   $a cmp $b
}

1;

__END__

The trick is to use the first value returned by caller(), the package 
name, to form the compound "fully qualified" names for $a and $b. The 
sub-pretty stuff there, ${$pkg.'::a'}, runs the risk of being 
interpreted as a soft reference, hence the local muting of the strict 
coding scolds.

After those four lines, $a and $b may be used as in any other sort 
sub, even though they're really locally scoped copies of the real 
things.

Now in another package, of any name:

#!perl -w
package Arbitrary; # Or none...

use Utils::Sort;
use strict;

my @list = qw{a G E k H b P y s A};

print sort case_order @list;

__END__

# AEGHPabksy

HTH

1;


-- 

   - Bruce

__bruce_van_allen__santa_cruz_ca__

Reply via email to