我可以将参数传递给Perl中的sort子例程吗?

时间:2010-10-22 09:32:17

标签: perl sorting compare

我正在使用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
}

我该怎么做?

2 个答案:

答案 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;

如果要在@_中传递要比较的元素,请将子例程的原型设置为($$)。注意:这比非原型子程序慢。