I think you have already found your bug here. Why would you expect $_ to be varying while this code is being executed.
The outermost foreach binds $word to each member of @words, and the while statement is checking the value of $from.
So, you tell me what the purpose of the if statement is.