in reply to $#array issue
while($index < $#array+1){ $last=pop(@array); [download]
You modify your @array while iterating over it. Don't.
Do you know what $#array holds after the first iteration?