Well the best practice is to not expect sort functions to be passable between packages.

But if you want to, here is an example of both how to write something that can return a sort function to another package (requires symbolic refs) and how to sort using a sort function from another package (requires eval):

use strict; print join "\n", Foo::sort_your_pack(Bar::ret_num_asc(), 1..10, -5..-3 +); package Foo; use Carp; # Takes a package. Will return a closure that generates sorts in that + package. { my %sort_gen; sub ret_sort_gen { my $pack = shift; my $set_evalname = "\n#line 1 \"'sorter for $pack'\""; return $sort_gen{$pack} ||= eval qq( $set_evalname package $pack; sub { my \$sort_fn = shift; unless (UNIVERSAL::isa(\$sort_fn, 'CODE')) { Carp::confess("Not a sort function"); } return sub {sort \$sort_fn \@_;} } ) || die $@; } } # Takes a sort function and a package. Returns a closure that sorts u +sing # that sort function in that package. sub sorter { my $sort_fn = shift; my $sort_gen = ret_sort_gen(shift || caller); return $sort_gen->($sort_fn); } # Example usage of the sorter subroutine. sub sort_your_pack { my $sorter = sorter(shift(@_), caller); return $sorter->(@_); } package Bar; # Takes an optional package. Returns a basic comparison function sub ret_num_asc { my $pack = shift || caller; no strict 'refs'; return sub {${"$pack\::a"} <=> ${"$pack\::b"}}; } __END__
The ease of setting up interesting sorts is not one of Perl's strengths.

In reply to Re (tilly) 5: $a and strict by tilly
in thread $a and strict by mce

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.