If it's of any interest. I went back to first principles and came up with this which verified correct and was about 12% quicker than your original.
@items = grep {
if (!exists $del{$_}) {
$i++;
1;
} else {
$index -= 1 if $i <= $index;
0 ;
}
} @items;
Then I realised that by pre-incrementing $i, it would never be zero so I could drop the 1;.
That the -= 1 if ($i <=$index) was identical to -=($i <= $index);
The 'then' part of the if could then be replaced with and and the else> with or.
The result is the improvement of +20% performance.
Whether the reduction in readability is worth it is a matter of choice and the application. If the list is big and the deletions frequent and it was running as part of a CGI for instance, it probably is. Other situations you have to judge on a case by case basis.
Personally, I would rather see 3 lines of comment explaining one efficient, (correct:) line of code, than 3 lines of self documenting code, but that is very much a personal preference.
Well It's better than the Abottoire, but Yorkshire! |