in reply to package globals and sort()

Eh? You will need to post code because it has nothing to do with $a and $b being in one package or another. You can see this example works fine.

You can declare a my $a or my $b in package main but not in package Sort as these vars need to be package globals there for sort() to work.

package Sort; # my($a,$b); # <<-- can't do that in this package sub my_num_sort { my $list_ref = shift; # return as a list ref for efficiency return [sort { $b <=> $a } @$list_ref]; } package main; # my($a,$b); # <<-- you can do this in this package (no sorts) my @list = ( 10, 42, 66, 1, 81, 32 ); # pass and return as a list ref for efficiency my $sorted = Sort::my_num_sort(\@list); print "$_ " for @$sorted;

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Replies are listed 'Best First'.
Re: Re: package globals and sort()
by Anonymous Monk on Apr 19, 2002 at 00:49 UTC
    Ah. Sorry. The method doesn't actually do the sort (too much copying for my tastes). It just defines the sort rules. Something like:
    package MyOrder; use strict; # export junk goes here... my %order = ( # order hash goes here... ); sub SortMyWay { if ( exists $order{$a} and exists $order{$b} ) { return $order{$a} <=> $order{$b} } elsif ( exists $order{$a} ) { return 1 } elsif ( exists $order{$b} ) { return -1 } else { return $a cmp $b } } package main; use strict; # use the module with the sort stuff in it, # which also exports sub SortMyWay my @foo = ( # stuff to sort goes here... ); my @bar = sort SortMyWay @foo;
    and of course I get an error. sigh. I wonder if AUTOLOAD could do it. I never used that before...

      Just do the actual sort in the MyOrder Package as shown. Note as we pass list references we pass 4 bytes in and 4 bytes out of the MyOrder package.

      package MyOrder; my %order = ( ); sub SortCriteria { if ( exists $order{$a} and exists $order{$b} ) { return $order{$a} <=> $order{$b} } elsif ( exists $order{$a} ) { return 1 } elsif ( exists $order{$b} ) { return -1 } else { return $a cmp $b } } sub SortMyWay { my $list_ref = shift; return [sort SortCriteria @$list_ref]; } package main; use strict; my @foo = qw( j a p h , ); my $bar = MyOrder::SortMyWay(\@foo); my @bar = @$bar; print "@bar";

      cheers

      tachyon

      s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

        Won't the @$list_ref cause an array copy? Not to mention the sort itself, and then again on the return. Forgive me, I was never all that clear where perl copies vs refs. Since the list is between 10,000 entries and 1,000,000 entries, I don't want to copy it any more then required.