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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.