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

Dav*_*d B 8 sorting perl compare

我正在使用sort我编写的定制比较子程序:

sub special_compare {
 # calc something using $a and $b
 # return value
}

my @sorted = sort special_compare @list;
Run Code Online (Sandbox Code Playgroud)

我知道它是最好用的$a,$b它是自动设置的,但有时我想让我special_compare得到更多的参数,即:

sub special_compare {
 my ($a, $b, @more) = @_; # or maybe 'my @more = @_;' ?
 # calc something using $a, $b and @more
 # return value
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

msc*_*cha 13

使用sort BLOCK LIST语法,请参阅perldoc -f sort.

如果你已经写了上面的special_compare子,你可以做,例如:

my @sorted = sort { special_compare($a, $b, @more) } @list;
Run Code Online (Sandbox Code Playgroud)

  • 您可能希望传递对"@ more"的引用以阻止它一直被复制. (3认同)