cutter has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I need to write to a file in a Unix format on a Win32 server using Activestate Perl. So that the \n gives me a Unix newline, not a ^M.

Looked at the open perdoc, perlfunc and googled without any luck, so thanks for any tips.

Replies are listed 'Best First'.
Re: Activestate open unix filehandle
by ikegami (Patriarch) on Mar 01, 2006 at 18:46 UTC

    Use binmode on your file handle. That will prevent LF from being transformed into CRLF.

    Update:

    Syntax example (using open syntax introduced in Perl 5.6.0):

    open(my $fh, '>', file); binmode($fh); print $fh ...

    Alternate syntax example (using open syntax introduced in Perl 5.8.0):

    require v5.8.0; open($fh, '>:raw', file); print $fh ...

    It works on STDOUT too:

    binmode(STDOUT); print ...
Re: Activestate open unix filehandle
by cutter (Acolyte) on Mar 01, 2006 at 20:13 UTC
    Using binmode worked fine, of course. Thanks for the help.
Re: Activestate open unix filehandle
by duff (Parson) on Mar 01, 2006 at 18:48 UTC

    You could do as ikegami says, or you could write an actual line feed character rather than \n. For example:

    my $LF = "\x0a"; print "This line ends with a linefeed" . $LF;

    update: Just do as ikegami says :-)

      That's incorrect. \n is \x0A in Windows. The convertion \x0A to \x0D\x0A happens in the PerlIO layers, so your trick doesn't work. Proof:

      >type !.pl my $LF = "\x0a"; print "This line ends with a linefeed" . $LF; >perl !.pl > ! >debug ! -rcx CX 0020 : -d100 l20 0B25:0100 54 68 69 73 20 6C 69 6E-65 20 65 6E 64 73 20 77 This line + ends w 0B25:0110 69 74 68 20 61 20 6C 69-6E 65 66 65 65 64 0D 0A ith a lin +efeed.. -q

        Indeed. I must be suffering a mild form of insanity. :-)