如何在模块中包含自定义排序功能?
例如,如果我创建以下脚本(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 my / 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 my / module.pm第20行(#1)
是否可以将$ a和$ b变量导出到模块中?
答案 0 :(得分:8)
$a
和$b
是程序包全局变量。在mysort
中有几种访问它们的选项,但是它们都是不好的。
您还可以使用原型变体:
sub mysort($$) {
my ($a, $b) = @_;
return $a cmp $b;
}
但是根据文档,此变体速度较慢。 http://perldoc.perl.org/functions/sort.html
答案 1 :(得分:4)
如果您出于某种原因不想在($$)
上添加mysort
原型(尽管我找不到一个很好的例子,就像@Ujin的答案一样),您也可以使用caller
获取呼叫者的程序包名称(假设呼叫者始终为sort
):
sub mysort {
my $pkg = caller;
{
no strict 'refs';
return ${"${pkg}::a"} cmp ${"${pkg}::b"};
}
}