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

Dear Monks,

Here is my perl script ...

#!/usr/bin/perl -w use strict; open( FH, ">junk.dat" ) or die "dang it!\n"; my $num = 1234; syswrite ( FH, $num ); close FH;
... Here's what is does ...
$ ./bi.pl

$ cat junk.dat
1234
... but want it to behave more like this C program ...

#include <stdio.h> main() { FILE *fh; int num = 1234; if(( fh = fopen( "junkc.dat", "w" ) ) == NULL ) { printf ("Cannot open it\n"); exit(); } fwrite( &num, sizeof(int), 1, fh); fclose( fh ); }
$ ./bi

$ cat junkc.dat
Ò

... why does my perl script write 1234 to junk.dat
and not the cool looking O thingy?

thanks

Replies are listed 'Best First'.
Re: writing binary data in perl
by dws (Chancellor) on Apr 11, 2002 at 22:24 UTC
    why does my perl script write 1234 to junk.dat and not the cool looking O thingy?

    You need to use pack() to get the number into a raw form.

    If you're on Win32, you'll also need to add   binmode(FH); to make binary work in general.

      Or chr(), as in perl -le 'print chr(1234&0xff).chr(1234>>8)'

        I think the chr(1234>>8) is superfluous.

        --
        John.

Re: writing binary data in perl
by jmcnamara (Monsignor) on Apr 12, 2002 at 07:38 UTC

    To write binary data like this you should use pack:
    #!/usr/bin/perl -w use strict; open( FH, ">junk.dat" ) or die "dang it!\n"; binmode FH; my $num = pack 'V',1234; print FH $num; close FH;

    If the program is going to be run on Windows as well you should also binmode the filehandle as shown above.

    --
    John.