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

I am writing binary files from scratch, but I cant write a byte 0x09 to a file as it gets interpreted as a tab and appears as 8 space characters 2020202020202020 instead.
This code running on Windows XP shows my problem
!/usr/bin/perl -w use strict; use diagnostics; my $file = 'test.dat'; open(FILE, ">:raw", "$file") or die "Could not open $file for writing: + $!\n"; binmode(FILE, ":raw"); my $tmp = 9; my $output = pack( 'C', $tmp ); print FILE $output; close FILE; print "...Created $file\n";
The file test.dat contains the following when viewed in hex
2020202020202020
I want it to contain
09
I am using Perl version
"This is perl, v5.8.7 built for MSWin32-x86-multi-thread"
Thanks
Al

Replies are listed 'Best First'.
Re: Binmode problem
by grep (Monsignor) on Jul 12, 2007 at 20:12 UTC
    I have a feeling you are opening the file with your editor before you check the for spaces. My bet is your editor is set to change tab to 8 spaces and then you're saving the change.

    Look at the file with hexdump before you do anything with it.

Re: Binmode problem
by ikegami (Patriarch) on Jul 12, 2007 at 22:26 UTC

    :raw/binmode isn't even needed, although it doesn't hurt either.

    >type 626330.pl open($fh, '>', '626330.txt'); print $fh "\t"; # or "\x09" or "\011" or pack('C', 9) >perl 626330.pl >dir 626330.txt ... 2007/07/12 06:20 PM 1 626330.txt <- file len = 1 ... >debug 626330.txt -rcx CX 0001 <- file len = 1 : -d100 l1 0AFD:0100 09 <- ASCII x09 = tab -q

    I concur with grep. You loaded the file in an editor that converted the tab to spaces.

      Thanks for the wisdom.
      Yes Slickedit was converting tab to spaces.
      In my real script which was a bit more complicated (creating wav files) than this example I was also using a printf of data containing %f which was interpreted as
      302E303030303030 hex or 0.000000
      which confused me. ie
      my @tmp = ( 0x25, 0x66 ); my $output = pack( 'C*',@tmp ); #print FILE $output; printf( FILE "$output" );

      Thanks again - all sorted now.
      Al