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, i.e.:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With