The while(@source) {} loop will result in an infinite loop unless you are removing elements of @source inside the while loop using pop() or shift().
In your case, since you have used variable index throughout the script, you can replace while(@source) with:
-
for($i=0; $i<=$#source; $i++) ## remove additional $i++; at the end of your loop
-
Other than this, the rest of the script seems fine and should work.