[英]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.