Can I pass arguments to the compare subroutine of sort in Perl?

﹥>﹥吖頭↗ 提交于 2019-12-08 16:29:21

问题


I'm using sort with a customized comparison subroutine I've written:

sub special_compare {
 # calc something using $a and $b
 # return value
}

my @sorted = sort special_compare @list;

I know it's best use $a and $b which are automatically set, but sometimes I'd like my special_compare to get more arguments, i.e.:

sub special_compare {
 my ($a, $b, @more) = @_; # or maybe 'my @more = @_;' ?
 # calc something using $a, $b and @more
 # return value
}

How can I do that?


回答1:


Use the sort BLOCK LIST syntax, see perldoc -f sort.

If you have written the above special_compare sub, you can do, for instance:

my @sorted = sort { special_compare($a, $b, @more) } @list;



回答2:


You can use closure in place of the sort subroutine:

my @more;
my $sub = sub {        
    # calc something using $a, $b and @more
};

my @sorted = sort $sub @list;

If you want to pass the elements to be compared in @_, set subroutine's prototype to ($$). Note: this is slower than unprototyped subroutine.



来源:https://stackoverflow.com/questions/3995537/can-i-pass-arguments-to-the-compare-subroutine-of-sort-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!