in reply to writing binary data in perl

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.

Replies are listed 'Best First'.
Re: Re: writing binary data in perl
by sfink (Deacon) on Apr 12, 2002 at 00:44 UTC
    Or chr(), as in perl -le 'print chr(1234&0xff).chr(1234>>8)'

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

      --
      John.

        What do you mean by "superfluous"? It's the closest analogue to writing out bytes from C, assuming you're on a little-endian machine.

        But the question was ambiguous about the desired outcome. Writing out the 'int' value 1234 might mean (1) writing either a little- or big-endian 0x4d2, (2) writing a host- or network-order 0x4d2, or (3) writing out the unicode codepoint 1234. I picked interpretation #1. #2 should be done with pack(), but since the sample C code didn't include htonl() or a variant, it apparently wasn't desired. #3 should be done with either pack() or a plain chr(1234).

        Except I'm still wrong, because I was really treating the 'int' as a 'short' and writing out only 16 bits. To match the C code, which wrote a 32-bit value, that should be chr(1234 & 0xff).chr(1234>>8).chr(0).chr(0) The distinction seemed unimportant for the simple goal of mentioning chr()!