[英]Can I pass arguments to the compare subroutine of sort in Perl?
我正在使用sort
编写的自定义比较子例程:
sub special_compare {
# calc something using $a and $b
# return value
}
my @sorted = sort special_compare @list;
我知道最好使用自动设置的$a
和$b
,但有时候我想让我的special_compare
获得更多的参数,即:
sub special_compare {
my ($a, $b, @more) = @_; # or maybe 'my @more = @_;' ?
# calc something using $a, $b and @more
# return value
}
我怎样才能做到这一点?
使用sort BLOCK LIST
语法,请参阅perldoc -f sort 。
如果你已经编写了上面的special_compare
sub,你可以这样做,例如:
my @sorted = sort { special_compare($a, $b, @more) } @list;
您可以使用闭包代替sort子例程:
my @more;
my $sub = sub {
# calc something using $a, $b and @more
};
my @sorted = sort $sub @list;
如果要在@_
传递要比较的元素,请将子例程的原型设置为($$)
。 注意:这比非原型子程序慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.