簡體   English   中英

我可以將參數傳遞給Perl中的sort子例程嗎?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM