Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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?

like image 829
David B Avatar asked Oct 22 '10 09:10

David B


2 Answers

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;
like image 62
mscha Avatar answered Oct 04 '22 05:10

mscha


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.

like image 35
Eugene Yarmash Avatar answered Oct 04 '22 05:10

Eugene Yarmash