我有一个脚本和一个像这样的包:
# 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 @_; }