in reply to Re: CRLF and Windows XP SP2
in thread CRLF and Windows XP SP2

Turning binmode on when writing the textfile fixes the problem. Amazing! But why? Why would you use binmode on a textfile? and When do you know if binmode is appropriate then?

Replies are listed 'Best First'.
Re^3: CRLF and Windows XP SP2
by Util (Priest) on Aug 12, 2005 at 19:44 UTC

    You would use binmode on a text file if it had (or needed to have) end-of-line characters (EOL) that are different than the EOL for the OS that is running the Perl program.

    The Newlines section in perlport has a detailed explanation of the nuances of line endings. Here is a short version: If you use the default IO mode, then Perl will try to hide the line-ending issue from you; on Win32, it does this by silently translating "\n" to "\r\n" when writing, and "\r\n" to "\n" when reading. Thus, "\n" can be considered a "virtual line ending" when using this method. If you change the mode to 'raw' (by using binmode or the three-argument form of open), then Perl will not alter the data as it passes through the IO layers, so you are responsible for knowing which line ending to use.

    So, on Win32:

    1. In the default mode, you should not see or say "\r"; your line ending will be "\n".
    2. In raw mode, you should see and say "\r\n". Also, set $/ to "\r\n", or chomp will trim off just the "\n" !

    The strange characters you are seeing in your editor are extra "\r"s. When you are in the default mode, and print "\r\n", it goes to disk as "\r\r\n".

      Perl will try to hide the line-ending issue from you; on Win32, it does this by silently translating "\n" to "\r\n" when writing
      And so, when you say \r\n, Perl translates the \n to \r\n, and you end up with \r\r\n, which is what's confusing your editor.