我正在使用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
}
我该怎么做?
答案 0 :(得分:13)
使用sort BLOCK LIST
语法,请参阅perldoc -f sort。
如果你已经写了上面的special_compare
sub,你可以这样做,例如:
my @sorted = sort { special_compare($a, $b, @more) } @list;
答案 1 :(得分:4)
您可以使用闭包代替sort子例程:
my @more;
my $sub = sub {
# calc something using $a, $b and @more
};
my @sorted = sort $sub @list;
如果要在@_
中传递要比较的元素,请将子例程的原型设置为($$)
。注意:这比非原型子程序慢。