http://www.perlmonks.org?node_id=971882


in reply to Native newline encoding

You probably really shouldn't do any detecting :)

You should be liberal in what you accept  s/[\r\n]+$//; and be strict in what you output  binmode  $fh, '...:crlf';

See also File::LocalizeNewlines and Encode::Newlines, PerlIO::eol and Devel::CheckOS

Replies are listed 'Best First'.
Re^2: Native newline encoding
by salva (Canon) on May 23, 2012 at 08:53 UTC
    Interestingly, Encode::Newlines does it as follows:
    use constant Native => ( ($^O =~ /^(?:MSWin|cygwin|dos|os2)/) ? CRLF : ($^O =~ /^MacOS/) ? CR : LF );

    I guess that this, which some special handling for VMS where the line ending is set by file and EDBCDI systems where line endings are the lesser problem, should cover 99% of the cases.

Re^2: Native newline encoding (more liberal)
by tye (Sage) on May 23, 2012 at 02:52 UTC
    s/[\r\n]+$­//;

    I much prefer s/\s*$//; because one should never write new code that causes trailing whitespace to be significant.

    be strict in what you output  binmode  $fh, '...:crlf'­;

    That seems like something that is quite unlikely to be what one should do. That might make sense when trying to use a Unix system to write a text file that will be used by some MS Windows program(s).

    For the most common case, you should replace that 'binmode' code with this code:

    - tye        

      That seems like something that is quite unlikely to be what one should do. That might make sense when trying to use a Unix system to write a text file that will be used by some MS Windows program(s).

      You mean like this exact situation? user wants notepad.exe to open .ini file and for it to work?

      For the most common case, you should replace that 'binmode' code with this code:

      What code?