简体   繁体   中英

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

I'm using sort with a customized comparison subroutine I've written:

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:

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 .

If you have written the above special_compare sub, you can do, for instance:

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

You can use closure in place of the sort subroutine:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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