perl - 如何在模块中包含排序功能?

标签 perl sorting module include global-variables

如何在模块中包含自定义排序功能?

例如,如果我创建以下脚本 (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;

它工作正常。但是,当我将它们拆分为 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;

和我/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;

我收到以下错误消息:
在字符串比较 (cmp) 中使用未初始化值 $my::module::a
我的/module.pm 第 20 行(#1)
(W 未初始化)一个未定义的值被使用,就好像它已经被使用一样
定义。它被解释为“”或 0,但可能是一个错误。
要抑制此警告,请为您的变量分配一个定义的值。
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.

在字符串比较 (cmp) 中使用未初始化的值 $my::module::b
我的/module.pm 第 20 行(#1)

有没有办法将 $a 和 $b 变量导出到模块中?

最佳答案

$a$b是包全局变量。在 mysort 中有几个访问它们的选项。但他们都有点不好。

您还可以使用原型(prototype)变体:

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

但是根据文档,此变体较慢。
http://perldoc.perl.org/functions/sort.html

关于perl - 如何在模块中包含排序功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53011793/

相关文章:

c - 使用指针对字符串进行排序

javascript - 获取随机的 n 个元素数组并将它们插入到指定元素中

java - 基于单独列表对列表进行排序

magento - 无效的配置字段后端模型: adminhtml/system_config_backend_web_secure_offloaderheader

performance - perl 是编写高性能页面的最快方法吗?

perl - 在 Perl 脚本中同时使用 ARGV 和 CGI

regex - 如何使用Regexp::Grammars匹配多行模式?

python - 共享模块变量没有更新?

perl - 如何制作一个为用户导入许多模块的模块?

regex - 如何从绑定(bind)标量变量的文件输出中过滤特定行?