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

hey again.

i need to store hexadecimal data to a file.
all i know so far is that
open (OUTPUT, ">hex.txt"); $data = 0x55; #eg print OUTPUT $data; close OUTPUT;
won't work, since it converts the hex value into decimal first and then stores it.
also it would be nice to store longer strings of hexadecimal data without an overflow.

thanks for your help, b4e

Replies are listed 'Best First'.
Re: storing hex data in a file
by dave_the_m (Monsignor) on Aug 11, 2004 at 12:14 UTC
    print chr(0x55)
    PS when you say 'hex', I think you mean 'binary'. Hex is an ASCII representation of binary data, which is why people gave you answers which were correct but not what you wanted.

    Dave.

Re: storing hex data in a file
by ccn (Vicar) on Aug 11, 2004 at 10:40 UTC

    print OUTPUT sprintf('0x%X', $data);

    see sprintf

Re: storing hex data in a file
by b4e (Sexton) on Aug 11, 2004 at 11:34 UTC
    thanks for your replies, but that's not quite what i wanted...

    your code stores "Ox55" in the file, ie. the hex value 30 78 35 35.

    what i need is to store the hex value (eg. 55, which would be 'U' in char.)
      You probably want to take a look at pack then.
      my $x = pack("C", 0x55); print $x, "\n";
      works for you specific case but I don't have a good grasp of your general case to know if it will work for that.
      Don't forget to use binmode() on your file handle if you're going to print out arbitrary values.
Re: storing hex data in a file
by doug (Pilgrim) on Aug 11, 2004 at 16:55 UTC
    In addition to what has been said, if you're doing this on windows, don't forget binmode(). Otherwise your binary won't turn out quite right.