繁体   English   中英

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

[英]How do I include a sort function in a module?

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

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

我收到以下错误消息:在我的/ module.pm第20行(#1)中使用未初始化的值$ my :: module :: a在字符串比较(cmp)中(未初始化)未使用的值如同它一样使用已定义。 它被解释为“”或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行(#1)的字符串比较(cmp)中使用未初始化的值$ my :: module :: b

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

$a$b是包全局变量。 有几个选项可以在mysort访问它们,但所有这些都很糟糕。

您还可以使用prototyped变体:

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

但根据文档,这个变种比较慢。 http://perldoc.perl.org/functions/sort.html

如果你出于某种原因不想在mysort上添加($$)原型(虽然我找不到想要的好例子),如@Ujin的答案,你也可以使用caller来获取包的名称调用者(假设调用者总是sort ):

sub mysort {
    my $pkg = caller;
    {
        no strict 'refs';
        return ${"${pkg}::a"} cmp ${"${pkg}::b"};
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM