You want to use "\n" if binmode isn't on.
You want to use "\r\n" if binmode is on.

use List::MoreUtils qw( apply ); for my $bin (0..1) { for my $eol ("\n", "\r", "\r\n") { my $name = $eol; $name =~ s/\r/cr/; $name =~ s/\n/lf/; $name .= '-bin' if $bin; { open(my $fh, '>', $name); binmode($fh) if $bin; print $fh map { "$_$eol" } qw( abc def ); } my $file = do { open(my $fh, '<', $name); binmode($fh); local $/; <$fh> }; my $data = join ' ', apply { s/\x0D/CR/ } apply { s/\x0A/LF/ } split //, $file; printf("%-9s %s\n", "$name:", $data); unlink($name); }}

output

lf: a b c CR LF d e f CR LF <- want cr: a b c CR d e f CR crlf: a b c CR CR LF d e f CR CR LF lf-bin: a b c LF d e f LF cr-bin: a b c CR d e f CR crlf-bin: a b c CR LF d e f CR LF <- want

Update: Simplified the code a bit.
Update: Oops, removed bug added in simplification. open(my $fh, '>', $file_name) defaults to :crlf, but open(my $fh, '>', \$file) does not!


In reply to Re: string replace with CRLF by ikegami
in thread string replace with CRLF by bobdole

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.