TGI has asked for the wisdom of the Perl Monks concerning the following question:

There is probably some simple, obvious thing I am missing here, but I can't seem to find the answer.

I wrote a quick & dirty script to generate test data for another program I am working on. I am trying to generate a barber pole and write it to a file. In this case byte 1 of the file should be 0x01, byte 2 should be 0x02 and so forth. A hex dump should look like this (for a 16 byte file):

0000000: 0102 0304 0506 0708 090a 0b0c 0d0e 0f10 ................

Pretty simple stuff, right? Here's my code:

use strict; use warnings; my $file = 'test.binary'; my $size = 16; #bytes to write to file; open ( my $fh, '>', $file ) or die "Unable to open $file - $!\n"; binmode $fh; my $byte = 0; for ( 1..$size ) { $byte++; $byte %= 256; my $char = pack 'C', $byte; # I tried both print and syswrite. I get the same results with ea +ch. syswrite( $fh, $char, 1); #print $fh $char; } close $fh; print "\nDONE\n";

My hex dump (for a 16 byte file) looks like this:

0000000: 0102 0304 0506 0708 090a 0b0c 0d0e 0f10 ................ 0000010: 0a .

Note the trailing 0x0a. If I set $bytes to 10, the hex dump is clean, no extra junk. If I set $bytes to 0, I get an empty file. If I set bytes to any other value I get a trailing 0x0a added for me. For some reason perl seems obsessed with forcing a trailing newline into the file.

I tested the script on perl 5.8.8 on win32 and 5.8.4 on a stock Debian Sarge system with the same results.

Update:

Thank you ikegami, you are absolutely correct.

I was using the handy hex editor in Vim to view my hex dumps. I had never noticed the extra 0x0A it was silently adding.


TGI says moo

Replies are listed 'Best First'.
Re: Newline appearing at the end of a file
by ikegami (Patriarch) on Jul 09, 2008 at 02:22 UTC

    That code should not — and indeed does not — add a newline.

    Windows:

    >debug test~1.bin -rcx CX 0010 : -d100 l10 0AE5:0100 01 02 03 04 05 06 07 08-09 0A 0B 0C 0D 0E 0F 10 ......... +....... -q

    Linux:

    $ od -t x1 test.binary 0000000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 0000020

    I suspect you opened the binary file with a text editor that always ends a file with a newline (as is the practice in unix) before doing the hex dump.