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
In reply to Newline appearing at the end of a file by TGI
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |