use Sort::Key qw(keysort rkeysort); my $sorter = $something ? \&rkeysort : \&keysort; foreach ($sorter->(sub { $_ }, @array) )