gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:26:14 24 4
gpt4 key购买 nike

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com