in reply to Substring1

How about adding this (untested) to the top of your while loop?
s/\s+\r/\r/g;
It should remove all whitespace immediately preceding a carriage return (\r or ^M).

--isotope