I've written a Perl script which runs in linux that copies an ascii text file to a new file, line terminators could be Windows style (\r\n) or Unix (\n). On certain lines which match a string I'm looking for I will process them before outputting that line back to the new file. On lines I don't process, doing a simple print OUTFILE $_; works great as it'll just replicate whatever line terminator the line uses and write that out to the output file. But for the lines I'm processing, I need to write back my processed line back out to it so I need to add in the line terminator manually. I'm doing this check right now:
my $endofline = ( /\r\n$/ ) ? "\r\n" : "\n";
Then here's the code for the processed line I'd write out:
print OUTFILE "$processed_string","$endofline";
My script works but I'm wondering if there's a better, cleaner way to do this? Currently I'm doing the end of line check within the while loop that processes each line of the input file so every single line is checked which is probably not efficient. I wanted to guard against the case where you could possibly have mixed windows and unix end of line terminators in the same file. However if that's extremely rare I guess I could remove the check from within the while loop that processes each line of the input file. If I do that, how would I get the type of line terminator the file uses so I know what to use in the print statement later? Basically is there a better way to do what I'm trying to do. Thanks for any tips.

In reply to Copying an ascii text file, replicating end of line terminator (windows or unix) by luckycat

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.