Subject: | BuiltinFunctions::ProhibitReverseSortBlock too strict |
BuiltinFunctions::ProhibitReverseSortBlock is based on PBP 152, which
particularly deprecates this code:
sort { $b cmp $a } @array;
Damian rightly says you should 'reverse sort' instead. Clearly the
policy should check for this.
Arguably, the policy can go a step further and generalize Damian's
advice to also forbid
sort { $b <=> $a } @array;
and require you to write instead
reverse sort { $a <=> $b } @array;
This is more controversial because a quick benchmark on perl-5.10.0
shows the reverse sort is about 40 times slower. But still, it is
perhaps more readable. Damian doesn't explicitly rule one way or the other.
But there are some cases where you really do need to compare $b and $a
the 'wrong way round'. For example,
my %h;
# Sort by lowest score first, or failing that, reverse alphabetical.
my @x = sort { $h{$a} <=> $h{$b} || $b cmp $a } keys %h;
# Hmm, perlcritic complains about that, perhaps I should say this:
my @y = reverse sort { $h{$b} <=> $h{$a} || $a cmp $b } keys %h;
But in both cases BuiltinFunctions::ProhibitReverseSortBlock complains!
Short of obfuscating the code somehow so it doesn't notice what is
going on in the sort block, I don't see how to satisfy it.
The PBP book doesn't issue a general prohibition on mentioning the
variable $b in a sort block before a mention of $a. It talks about the
particular common error of sort { $b cmp $a }. So I think this policy
needs to be weakened.