in reply to $#array issue

while($index < $#array+1){ $last=pop(@array);

You modify your @array while iterating over it. Don't.

Do you know what $#array holds after the first iteration?