in reply to Hex format conversion in Perl

Various ways. But perl doesn't care if you mess with strings or hexs.
#reading local $/ = undef; #trick to read all data in one swoop open FILE, $myfile; my $hex = <FILE>; #or writing: open FILE, ">$myfile"; print FILE $tiff_data;
If you are on win32, check binmode.

Hope this helps,

Jeroen
"We are not alone"(FZ)

Replies are listed 'Best First'.
Re: Re: Hex format conversion in Perl
by epoptai (Curate) on Apr 19, 2001 at 19:20 UTC
    jeroenes, did you forget the hex conversion?
    (his reply is now below)
    # reading (for example, a gif) local $/ = undef; open FILE, $file; binmode(FILE); # needed for win32 $gif = <FILE>; $hexgif = unpack ("H*", $gif); # convert gif to hex string # printing $gif = pack ("H*", $hexgif); # convert hex string back to binary data print "Content-type: image/gif\n\n"; binmode(STDOUT); print $gif;

    Update: jeroenes is right about the size consideration. You asked for hex so that's what this code does. But a hex string is double the size of the binary data is encodes. Here are the results of some different methods for encoding binary data as text:

    bytesformat% of original
    5008 original jpeg 100.00%
    10016 hex string 200.00%
    6904 uuencoded 137.86%
    6768 base64 135.14%
    6706 zlib/uuencoded 133.91%
    6574 zlib/base64 131.27%
    4865 zlib (binary) 97.14%

      Not forgotten.
      IMHO, you don't need that conversion at all, unless there is another reason/problem. Perl has no trouble with a string like the first $gif in your code.

      Why would you want an extra conversion step? Maybe you like to dump the hex-string on a terminal, readible to the human eye? Insert it in an e-mail (base64 would be better in that case)? Does the database only accept ASCII strings (BerkeleyDB eg does accept them)?

      But if you just want to redirect the data in a perlish way, just keep with the unconverted 1-byte wide strings.

      Jeroen
      "We are not alone"(FZ)
      Update: epoptai CB'd me an alternative explanation of the posting, that makes more sense. His code will do. But, consider pack 'u*', $gif;, CGIPack or MIME::Base64 to pack your strings, as that shortens the strings somewhat.