gpt4 book ai didi

perl - 使用来自另一个包的排序子程序

转载 作者:行者123 更新时间:2023-12-04 05:25:22 34 4
gpt4 key购买 nike

我有一个脚本和一个包,如下所示:

# file: sortscript.pl
use strict;
use warnings;
use SortPackage;

my @arrays = ([1,"array1"],[10,"array3"],[4,"array2"]);

print "Using sort outside package\n";
foreach (sort SortPackage::simplesort @arrays){
print $_->[1],"\n";
}

print "\nUsing sort in same package\n";
SortPackage::sort_from_same_package(@arrays);

——
# file: SortPackage.pm
use strict;
use warnings;
package SortPackage;

sub simplesort{
return ($a->[0] <=> $b->[0]);
}

sub sort_from_same_package{
my @arrs = @_;
foreach (sort simplesort @arrs){
print $_->[1],"\n";
}
}
1;

运行脚本产生输出:
$ perl sortscript.pl
Using sort outside package
Use of uninitialized value in numeric comparison (<=>) at SortPackage.pm line 15.
Use of uninitialized value in numeric comparison (<=>) at SortPackage.pm line 15.
Use of uninitialized value in numeric comparison (<=>) at SortPackage.pm line 15.
Use of uninitialized value in numeric comparison (<=>) at SortPackage.pm line 15.
Use of uninitialized value in numeric comparison (<=>) at SortPackage.pm line 15.
Use of uninitialized value in numeric comparison (<=>) at SortPackage.pm line 15.
array1
array3
array2

Using sort in same package
array1
array2
array3

当子程序在另一个包中时,为什么我不能正确使用它进行排序?

最佳答案

如前所述,$a$b是包全局变量,因此另一种解决方案是将调用站点的全局变量临时别名为包 SortPackage 中的全局变量。 :

{
local (*a, *b) = (*SortPackage::a, *SortPackage::b);
foreach (sort SortPackage::simplesort @arrays){
print $_->[1],"\n";
}
}

但这当然很丑陋。我只要 SortPackage导出一个完整的排序例程,而不仅仅是一个比较器:
package SortPackage;
use strict;

sub _sort_by_first_element_comparator {
return $a->[0] <=> $b->[0];
}

sub sort_by_first_element {
return sort _sort_by_first_element_comparator @_;
}

关于perl - 使用来自另一个包的排序子程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11508333/

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