如何在模块中包含自定义排序函数?
例如,如果我创建了以下脚本(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;
我得到了以下错误信息: 在 my/module.pm 的第20行,使用未初始化的值$my::module::a进行字符串比较 (cmp) (#1) (W uninitialized) 使用未定义的值,就像它已经被定义一样。它被解释为“”或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.
在my/module.pm第20行,使用未初始化的变量$my::module::b进行了字符串比较(cmp),出现警告(#1)。
是否有一种方法可以将$a和$b变量导出到模块中?
use diagnostics
。它会增加约一秒的启动时间。 - simbabquemysort
被导出到主包中,它想要在主包中使用$a
和$b
变量,但是mysort
中的$a
和$b
变量指的是$my::module::a
和$my::module::b
,这些变量在该包中没有声明,并且不作为sort
的特殊变量使用。请注意,您可以使用$::a
和$::b
来引用主包中的$a
和$b
变量,但是如果您将mysort
导入到除main
包之外的其他包中,则此方法将无法正常工作。@Ujin提供了更好的方法,这个方法通常都能正常工作。 - Håkon Hæglandsort
也是可以的。 - Guido Flohr