in reply to CRLF and Windows XP SP2

When I run this code

open (FH,'>',"linefeed.txt"); # binmode FH; # I have added this line print FH "This is a line\r\n" __END__ This is a line^M (viewed under gvim on win XP SP 2)
Uncomment the binmode FH and re-run

Output

This is a line (NOTE: no ^M)<p>

perldoc -f binmode On some systems (in general, DOS and Windows-based systems) binmode() +is necessary when you're not working with a text file. For the sake +of portability it is a good idea to always use it when appropriate, a +nd to never use it when it isn't appropriate.

update: Guess I am joining this thread a bit late now!

As others have mentioned CRLF translation is done automatically by Perl. So you are better off using \n in windows and Perl will take care of the rest.

OK what's the scoop with binmode and why did the problem go away?

The reason is that binmode() does not translate \n => CRLF and rather does \n=>LF. Since you are doing \r\n it becomes => CR(i.e. \r)LF(i.e.\n) in binmode!

-SK

Replies are listed 'Best First'.
Re^2: CRLF and Windows XP SP2
by slloyd (Hermit) on Aug 12, 2005 at 18:47 UTC
    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?

      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.