By default, perl prints \r\n in a win32 environment. How can I override this? I'm using perl to make some changes to some source code in a repository, and I don't want to change all the newline characters.
I tried changing the output record separator but with no luck.
Thanks!
Edit: Wanted to include a code sample - I'm doing a search and replace over some files that follow a relatively straightforward pattern like this:
#!/usr/bin/perl
# test.pl
use strict;
use warnings;
$/ = undef;
$\ = "\n";
$^I=".old~";
while (<>) {
while (s/hello/world/) {
}
print;
}
This should replace any instances of "hello" with "world" for any files passed on the cmd line.
Edit 2: I tried the binmode
as suggested without any luck initially. I delved a bit more and found that $^I
(the inplace edit special variable) was overriding binmode
. Any work around to still be able to use the inplace edit?
Edit 3: As Sinan points out below, I needed to use binmode ARGVOUT
with $^I
instead of binmode STDOUT
in my example. Thanks.
The Perl print function\n"; Notice that you need to supply the newline character at the end of your string. If you don't supply that newline character, and print multiple lines, they'll all end up on one long line of output, like this: Hello, world.
Perl is portable and cross-platform. At the time of this writing, Perl can run on over 100 platforms. Perl is good for mission-critical large-scale projects as well as rapid prototyping.
Printing "\n"
to a filehandle on Windows emits, by default, a CARRIAGE RETURN
("\015"
) followed by a LINE FEED
("\012"
) character because that the standard newline sequence on Windows.
This happens transparently, so you need to override it for the special filehandle ARGVOUT
(see perldoc perlvar):
#!/usr/bin/perl -i.bak
use strict; use warnings;
local ($\, $/);
while (<>) {
binmode ARGVOUT;
print;
}
Output:
C:\Temp> xxd test.txt 0000000: 7465 7374 0d0a 0d0a test.... C:\Temp> h test.txt C:\Temp> xxd test.txt 0000000: 7465 7374 0a0a test..
See also perldoc open, perldoc binmode and perldoc perliol (thanks daotoad).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With