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

I have the following: ewh2442 018234 35.67 (alpha-numeric, integer, floating). I'm trying to figure out the correct pack command format to write these three fields in binary format to an external file. I believe the "pack" command is the right one but I'm unclear as to the format of it. Suggestions?

Replies are listed 'Best First'.
Re: pack function
by BrowserUk (Patriarch) on May 07, 2010 at 19:02 UTC

    There are many ways to pack that, depending upon what is going to read it back and the ranges of the values.

    For example, if you are reading it back in the same or another script; the ineteger is unsigned and you want to retains full double precision, then:

    $packed = pack 'C/A* N d', 'ewh2442', '018234', 35.67;; print for unpack 'C/A* N d', $packed;; ewh2442 18234 35.67

    But if another program is reading it back and is expecting a particular format; or if the string has to be a fixed length; or if the integer is signed; or if the integer can only range up to +-32767/0-65535; or you don't want to use 8-bytes for each float but rather only for; or if the reader is going to be on a different platform which uses a different endianess; then you might would need a different template.

    Essentially you need to tell us a lot more before we can give you definitive help.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: pack function
by almut (Canon) on May 07, 2010 at 18:55 UTC

    Your question cannot really be answered without knowing what binary format you need. For example, you could pack the integer into 16, 32 or 64 bits, in little- or big-endian format etc. Similarly for the other types.

    Depending on what you need, you'd pick the respective letters (as documented in pack) for the format template, e.g. 'N' if you want the integer to be stored as an unsigned 32-bit value in big-endian order...

Re: pack function
by Marshall (Canon) on May 07, 2010 at 20:12 UTC
    You haven't specified a format for the binary file. With data like that, why isn't just ASCII good enough? Let the other programs that need to understand this data parse the ASCII into their own internal format...why not? There can be huge advantages to having a "human readable" data interchange format. Nowadays squeezing the data into the minimum number of bytes just isn't as important as it used to be.