Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

How do I use a sort routine from a different package/module?

by bobf (Monsignor)
on Jun 09, 2005 at 07:33 UTC ( [id://464989]=perlquestion: print w/replies, xml ) Need Help??

bobf has asked for the wisdom of the Perl Monks concerning the following question: (sorting)

How do I use a sort routine from a different package/module?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I use a sort routine from a different package/module?
by bobf (Monsignor) on Jun 09, 2005 at 07:34 UTC

    There are (at least) two ways to access sort routines in a different package:

    • Prototype the sort subfunction and pass the values as arguments, which can then be accessed by directly indexing @_
    • Fully qualifying $a and $b in the sort routine with the package name of the caller (this works because prior to Perl 6 the elements to be compared are passed to the sort routine in the package global variables $a and $b)

    use strict; use warnings; use my_sort_routines; package myprogram; my @data = ( 4, 2, 1, 3 ); my @sorted_proto = sort my_sort_routines::prototyped @data; my @sorted_qual = sort my_sort_routines::qualify_pkg @data; print @sorted_proto, "\n"; #1234 print @sorted_qual, "\n"; #1234 package my_sort_routines; sub prototyped ($$) { # Access the arguments directly by indexing @_ $_[0] <=> $_[1]; } sub qualify_pkg { # Qualify $a and $b with the name of the calling package # Symbolic refs require "no strict refs" here # Symbol::qualify could simplify this, but this illustrates # how to do it without an additional module my $pkg = caller; no strict 'refs'; ${"${pkg}::a"} <=> ${"${pkg}::b"}; }

    Links:

      there is an obvious third way: let the sub on the other package do the full sort, not just the comparison!

      This would also allow for further optimizations (i.e., using the ST) when the data requires it.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://464989]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2024-03-19 06:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found