Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print just a unix newline in Perl on Win32?

Tags:

newline

perl

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.

like image 879
Keith Bentrup Avatar asked Nov 30 '09 15:11

Keith Bentrup


People also ask

How do I print a newline in Perl?

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.

Is Perl portable?

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.


1 Answers

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).

like image 185
Sinan Ünür Avatar answered Oct 11 '22 18:10

Sinan Ünür