perl – 使用另一个包中的排序子例程

前端之家收集整理的这篇文章主要介绍了perl – 使用另一个包中的排序子例程前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个脚本和一个像这样的包:
# 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相关文章