简体   繁体   English

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

[英]Can I pass arguments to the compare subroutine of sort in Perl?

I'm using sort with a customized comparison subroutine I've written: 我正在使用sort编写的自定义比较子例程:

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

my @sorted = sort special_compare @list;

I know it's best use $a and $b which are automatically set, but sometimes I'd like my special_compare to get more arguments, ie: 我知道最好使用自动设置的$a$b ,但有时候我想让我的special_compare获得更多的参数,即:

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

How can I do that? 我怎样才能做到这一点?

Use the sort BLOCK LIST syntax, see perldoc -f sort . 使用sort BLOCK LIST语法,请参阅perldoc -f sort

If you have written the above special_compare sub, you can do, for instance: 如果你已经编写了上面的special_compare sub,你可以这样做,例如:

my @sorted = sort { special_compare($a, $b, @more) } @list;

You can use closure in place of the sort subroutine: 您可以使用闭包代替sort子例程:

my @more;
my $sub = sub {        
    # calc something using $a, $b and @more
};

my @sorted = sort $sub @list;

If you want to pass the elements to be compared in @_ , set subroutine's prototype to ($$) . 如果要在@_传递要比较的元素,请将子例程的原型设置为($$) Note: this is slower than unprototyped subroutine. 注意:这比非原型子程序慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM