in reply to Variable messes up loops.

Not sure if that will help, but you might try to localize $/ before changing its value (i. e. say  local $/; and enclose it in a block). BTW., does the script read all lines of the file if you comment out the statements where you set $/?