I believe this is due to the fact that in perl, when you iterate over an array, each element is passed by reference, which means that when $ i changes in a loop, it changes the actual value in the array. I am not sure how to do this at the expense of cost.
source share