Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with printing newlines

Status
Not open for further replies.

neomage

Programmer
May 12, 2007
1
US
First, to clear up any ambiguity, I'm going to call the ASCII character with a hex code of 0A and a decimal code of 10 a "LF" .

I'm also going to call the ASCII character with a hex code of 0D and a and a decimal code of 15 a "CR".

I want to be able to print just a "LF" to a file. As a simple test case:

open TEST, ">", "test.data";
select TEST;
print "A" . chr(hex("0A")) . "B" . "\n" . "C" . "\r" . "D";
close TEST;

Logically, when I look at the test.data file with a hex editor I'd expect just a "LF" between the A and B, but instead there are is a "CR" followed by an "LF."

For reference here is the hex output of my test script and the equivalent chars below the hex number:

41 0D 0A 42 0D 0A 43 0D 44
A CR LF B CR LF C CR D

I was expecting only a "LF" (i.e., 0A) between the "A" (41) and "B" (42) ...

If it helps this is Perl 5.8.8 (ActiveState Perl Build 820) on Windows XP.

Thanks for any advice you may be able to give me.
 
You need to specify binmode for the file if you're running on DOS/Windows.

Code:
open TEST, ">", "test.data";
[COLOR=red][b]binmode TEST;[/b][/color]
select TEST;
print "A" . chr(hex("0A")) . "B" . "\n" . "C" . "\r" . "D";
close TEST;

 
The \n in Perl is OS-aware, so in Windows it's CRLF, in *nix it's LF, and on a Mac it's CR. Most of the time this 'helpful' behaviour is what you want, and makes your scripts portable. If not, use binmode as brigamar suggests.

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top