Search code examples
perlsortingmoduleincludeglobal-variables

How do I include a sort function in a module?


How do I include a custom sort function in a module?

For example, if I create the following script (test.pl):

#!/usr/bin/perl

use 5.022;
use warnings;
use diagnostics;
use utf8;
use open qw(:std :utf8);
binmode STDOUT, ":utf8";
binmode STDERR, ":utf8";

sub mysort {
    return $a cmp $b;
}

my @list = ('a', 'd', 'b', 'c');
say join "\n", sort mysort @list;

It works fine. However when I split them up into test.pl:

#!/usr/bin/perl

use 5.022;
use warnings;
use diagnostics;
use utf8;
use open qw(:std :utf8);
binmode STDOUT, ":utf8";
binmode STDERR, ":utf8";

use my::module;

my @list = ('a', 'd', 'b', 'c');
say join "\n", sort mysort @list;

and my/module.pm:

package my::module;
use 5.022;
use warnings;
use diagnostics;
use utf8;
use open qw(:std :utf8);
binmode STDOUT, ':utf8';
binmode STDERR, ':utf8';

BEGIN {
    my @exp = 'mysort';
    require Exporter;
    our $VERSION   = 1.00;
    our @ISA       = 'Exporter';
    our @EXPORT = @exp;
    our @EXPORT_OK = @exp;
}

sub mysort {
    return $a cmp $b;
}

1;

I get the following error message: Use of uninitialized value $my::module::a in string comparison (cmp) at my/module.pm line 20 (#1) (W uninitialized) An undefined value was used as if it were already defined. It was interpreted as a "" or a 0, but maybe it was a mistake. To suppress this warning assign a defined value to your variables.

To help you figure out what was undefined, perl will try to tell you
the name of the variable (if any) that was undefined.  In some cases
it cannot do this, so it also tells you what operation you used the
undefined value in.  Note, however, that perl optimizes your program
and the operation displayed in the warning may not necessarily appear
literally in your program.  For example, "that $foo" is usually
optimized into "that " . $foo, and the warning will refer to the
concatenation (.) operator, even though there is no . in
your program.

Use of uninitialized value $my::module::b in string comparison (cmp) at my/module.pm line 20 (#1)

Is there a way to export the $a and $b variables into the module?


Solution

  • $a and $b are package global variables. There are several options to access them in mysort but all of them are kind of bad.

    You can also use prototyped variant:

    sub mysort($$) {
        my ($a, $b) = @_;
        return $a cmp $b;
    }
    

    But according to the documentation this variant is slower. http://perldoc.perl.org/functions/sort.html