First of all, you don't even try to change the CRLF to LF. You just print back out what you got.
On a Windows system, Perl adds the :crlf
layer to your file handles. That means that CRLF gets changed to LF on read, and LF gets changed to CRLF on write.
That last bit is the problem. By default, Perl assumes you're create a text file, but what you're creating doesn't match the definition of a text file on Windows. As such, you need to switch your output to binmode
.
Solution that only works on a Windows system:
use strict;
use warnings;
binmode(STDOUT);
open(my $fh, '<', 'file.txt') or die $!;
print while <$fh>;
Or if you want it to work on any system,
use strict;
use warnings;
binmode(STDOUT);
open(my $fh, '<', 'file.txt') or die $!;
while (<$fh>) {
s/\r?\n\z//;
print "$_\n";
}
Without binmode on the input,
- You'll get CRLF for CRLF on a non-Windows system.
- You'll get LF for CRLF on a Windows system.
- You'll get LF for LF on all systems.
s/\r?\n\z//
handles all of those.