PERLPACKTUT(1)         Perl Programmers Reference Guide         PERLPACKTUT(1)


       perlpacktut - tutorial on "pack" and "unpack"


       and some well-defined representation as might be required in the envi-
       ronment of a Perl program. Unfortunately, they’re also two of the most
       misunderstood and most often overlooked functions that Perl provides.
       This tutorial will demystify them for you.

The Basic Principle

       Most programming languages don’t shelter the memory where variables are
       your heart’s content.

       In Perl, you just can’t access memory at random, but the structural and
       sequence containing representations according to a given specification,
       deriving some values from the contents of a string of bytes. (Be cau-
       tioned, however, that not all that has been packed together can be
       neatly unpacked - a very common experience as seasoned travellers are
       likely to confirm.)

       Why, you may ask, would you need a chunk of memory containing some val-
       ues in binary representation? One good reason is input and output
       binary representation is either forced on you or will give you some
       benefit in processing. Another cause is passing data to some system
       judicious usage of these two functions.

       To see how (un)packing works, we’ll start with a simple template code
       sequence and a string of hexadecimal digits. Let’s use "unpack", since
       message unfortunate programs are wont to throw at you before they
       a sequence of bytes that we’d like to inspect without assuming anything
       about its meaning, we can write

          my( $hex ) = unpack( ’H*’, $mem );
          print "$hex\n";

       whereupon we might see something like this, with each pair of hex dig-
       its corresponding to a byte:


       both? Assuming that we’re on a computer where ASCII (or some similar)
       is a pretty vague indication of quantity, "H" has been defined to con-
       vert just a single hexadecimal digit unless it is followed by a repeat

       The inverse operation - packing byte contents from a string of hexadec-
       imal digits - is just as easily written. For instance:

          my $s = pack( ’H2’ x 10, map { "3$_" } ( 0..9 ) );
          print "$s\n";

       pack template should contain ten pack codes. If this is run on a com-
       puter with ASCII character coding, it will print 0123456789.

Packing Text

       Let’s suppose you’ve got to read in a data file like this:

           Date      │Description                │ Income│Expenditure
           01/24/2001 Ahmed’s Camel Emporium                  1147.99
           01/28/2001 Flea spray                                24.99
           01/29/2001 Camel rides to tourists      235.00

       "split" collapses blank fields, you’ll never know whether a record was

           while (<>) {

       It’s not really a barrel of laughs, is it? In fact, it’s worse than it
       10 characters wide, and the error has propagated right through the
       other numbers - which we’ve had to count by hand. So it’s error-prone
       as well as horribly unfriendly.

       Or maybe we could use regular expressions:

           while (<>) {

       Urgh. Well, it’s a bit better, but - well, would you want to maintain

       Hey, isn’t Perl supposed to make this sort of thing easy? Well, it
       help you out when dealing with fixed-width data like the above. Let’s
       have a look at a solution with "unpack":

           while (<>) {

       That looks a bit nicer; but we’ve got to take apart that weird tem-
       plate.  Where did I pull that out of?

       OK, let’s have a look at some of our data again; in fact, we’ll include

                    1         2         3         4         5
           Date      │Description                │ Income│Expenditure
           01/28/2001 Flea spray                                24.99
           01/29/2001 Camel rides to tourists      235.00

       we could say this:


       OK, what’s next? Between the date and the description is a blank col-
       umn; we want to skip over that. The "x" template means "skip forward",
       from 12 to 38. That’s 27 more characters, hence "A27". (Don’t make the
       Count ’em!)



       not expenditure might end at column 46. Hence, we don’t want to tell
       our "unpack" pattern that we need to find another 12 characters; we’ll
       just say "if there’s anything left, take it". As you might guess from
       regular expressions, that’s what the "*" means: "use everything remain-

       ·  Be warned, though, that unlike regular expressions, if the "unpack"
          template doesn’t match the incoming data, Perl will scream and die.

       Hence, putting it all together:


       Now, that’s our data parsed. I suppose what we might want to do now is
       our ledger - in the same format - saying how much we’ve brought in and
       how much we’ve spent:

           while (<>) {
               $tot_income += $income;
               $tot_expend += $expend;



           # OK, let’s go:


       Oh, hmm. That didn’t quite work. Let’s see what happened:

           01/24/2001 Ahmed’s Camel Emporium                   1147.99
           01/28/2001 Flea spray                                 24.99
           01/29/2001 Camel rides to tourists     1235.00
           03/23/2001Totals                     1235.001172.98

       OK, it’s a start, but what happened to the spaces? We put "x", didn’t
       we? Shouldn’t it skip forward? Let’s look at what "pack" in perlfunc

           x   A null byte.

       Urgh. No wonder. There’s a big difference between "a null byte", char-
       acter zero, and "a space", character 32. Perl’s put something between
       the date and the description - but unfortunately, we can’t see it!

       additional spaces to line up our fields, like this:


       but they don’t translate to spaces in the output.) Here’s what we got
       this time:

           01/24/2001 Ahmed’s Camel Emporium                   1147.99
           01/28/2001 Flea spray                                 24.99
           01/29/2001 Camel rides to tourists     1235.00
           03/23/2001 Totals                      1235.00 1172.98

       That’s a bit better, but we still have that last column which needs to
       be moved further over. There’s an easy way to fix this up: unfortu-
       nately, we can’t get "pack" to right-justify our fields, but we can get
       "sprintf" to do it:


       This time we get the right answer:

           01/28/2001 Flea spray                                 24.99
           01/29/2001 Camel rides to tourists     1235.00
           03/23/2001 Totals                      1235.00      1172.98

       So that’s how we consume and produce fixed-width data. Let’s recap what
       we’ve seen of "pack" and "unpack" so far:

       ·  Use "pack" to go from several pieces of data to one fixed-width ver-
          sion; use "unpack" to turn a fixed-width-format string into several
          pieces of data.

       ·  The pack format "A" means "any character"; if you’re "pack"ing and
          you’ve run out of things to pack, "pack" will fill the rest up with

          "introduce a null byte" - that’s probably not what you mean if
          you’re dealing with plain text.

       ·  You can follow the formats with numbers to say how many characters

       ·  Instead of a number, you can use "*" to mean "consume everything
          else left".

          "consume all of the current piece of data". That’s to say


          second. This is a general principle: each format character corre-
          sponds to one piece of data to be "pack"ed.

Packing Numbers

       So much for textual data. Let’s get onto the meaty stuff that "pack"
       but Perl will do all the finicky labor for you.


       Packing and unpacking numbers implies conversion to and from some spe-
       cific binary representation. Leaving floating point numbers aside for
       the moment, the salient properties of any such representation are:

       ·   the number of bytes used for storing the integer,

       ·   whether the contents are interpreted as a signed or unsigned num-

       ·   the byte ordering: whether the first byte is the least or most sig-
           nificant byte (or: little-endian or big-endian, respectively).

       So, for instance, to pack 20302 to a signed 16 bit integer in your com-
       puter’s representation you write

          my $ps = pack( ’s’, 20302 );

       or "NO" (depending on your system’s byte ordering) - or something
       entirely different if your computer doesn’t use ASCII character encod-
       ing.  Unpacking $ps with the same template returns the original integer

          my( $s ) = unpack( ’s’, $ps );

       This is true for all numeric template codes. But don’t expect miracles:
       are silently discarded, and unpack certainly won’t be able to pull them
       set, and unpacking this will smartly return a negative value.

       16 bits won’t get you too far with integers, but there is "l" and "L"
       your system supports 64 bit integers you can push the limits much
       as a local C compiler returns for "sizeof(int)", but it’ll use at least
       32 bits.

       write binary files. What you’ll need in this case are template codes
       that depend on what your local C compiler compiles when you code
       standard leaves much leeway with respect to the relative sizes of these
       data types, actual values may vary, and that’s why the values are given
       as expressions in C and Perl. (If you’d like to use values from %Config

          signed unsigned  byte length in C   byte length in Perl

       The "i!" and "I!" codes aren’t different from "i" and "I"; they are
       tolerated for completeness’ sake.

       Unpacking a Stack Frame

       Requesting a particular byte ordering may be necessary when you work
       with binary data coming from some specific architecture whereas your

        TOS: │   IP    │  TOS+4:│ FL │ FH │ FLAGS  TOS+14:│   SI    │
             │   CS    │        │ AL │ AH │ AX            │   DI    │
                                │ BL │ BH │ BX            │   BP    │
                                │ CL │ CH │ CX            │   DS    │
                                │ DL │ DH │ DX            │   ES    │

       order, and that’s why the low order byte is stored at the lower
       address. To unpack such a (signed) short we’ll have to use code "v". A
       repeat count unpacks all 12 shorts:

            unpack( ’v12’, $frame );

       Alternatively, we could have used "C" to unpack the individually acces-
       sible byte registers FL, FH, AL, AH, etc.:

            unpack( ’C10’, substr( $frame, 4, 10 ) );

       back up a little, and then unpack 2 bytes. Since Perl is nice, it prof-
       fers the template code "X" to back up one byte. Putting this all
       together, we may now write:

          my( $ip, $cs,
          unpack( ’v2’ . (’vXXCC’ x 5) . ’v5’, $frame );


       We’ve taken some pains to construct the template so that it matches the
       contents of our frame buffer. Otherwise we’d either get undefined val-
       will supply null strings (which are coerced into zeroes whenever the
       pack code says so).

       How to Eat an Egg on a Net

       know that your data comes from a compliant architecture, but, surpris-
       ingly enough, you should also use these pack codes if you exchange
       Lilliputian parties and may well influence the political development

          my $buf = pack( ’N’, length( $msg ) ) . $msg;

       or even:

          my $buf = pack( ’NA*’, length( $msg ), $msg );

       really code this!)

       Floating point Numbers

       For packing floating point numbers you have the choice between the pack
       codes "f" and "d" which pack into (or unpack from) single-precision or
       double-precision representation as it is provided by your system.
       you want to send your real numbers across computer boundaries, you’d
       better stick to ASCII representation, unless you’re absolutely sure
       what’s on the other end of the line.)

Exotic Templates

       Bit Strings

       have to be used either as a last resort or because it is the most con-
       venient way to handle your data. Bit string (un)packing converts
       between strings containing a series of 0 and 1 characters and a
       byte may be written as a bit string. Let’s have a look at an annotated

            7 6 5 4 3 2 1 0
          │ 1 0 0 0 1 1 0 0 │
           MSB           LSB

       It’s egg-eating all over again: Some think that as a bit string this
       bit, others insist on "00110001". Well, Perl isn’t biased, so that’s
       why we have two bit string codes:

          $byte = pack( ’B8’, ’10001100’ ); # start with MSB
          $byte = pack( ’b8’, ’00110001’ ); # start with LSB

       catenation on unpacked bit strings.)

       To illustrate unpacking for bit strings, we’ll decompose a simple sta-
       tus register (a "-" stands for a "reserved" bit):

          │ S Z - A - P - C │ - - - - O D I T │
           MSB           LSB MSB           LSB

       Converting these two bytes to a string can be done with the unpack tem-
       plate ’b16’. To obtain the individual bit values from the bit string we
       individual characters. Bit values from the "reserved" positions are
       simply assigned to "undef", a convenient notation for "I don’t care
       where this goes".

             split( //, unpack( ’b16’, $status ) );

       We could have used an unpack template ’b12’ just as well, since the
       last 4 bits can be ignored anyway.


       you won’t ever need this encoding technique which was invented to over-
       come the shortcomings of old-fashioned transmission mediums that do not
       you select pack code "u" on the menu:

          my $uubuf = pack( ’u’, $bindat );

       A repeat count after "u" sets the number of bytes to put into an uuen-
       coded line, which is the maximum of 45 by default, but could be set to
       repeat count.

       Doing Sums

       An even stranger template code is "%"<number>. First, because it’s used
       used in "pack" at all, and third, in "unpack", doesn’t return the data
       as defined by the template code it precedes. Instead it’ll give you an

           my $buf = pack( ’iii’, 100, 20, 3 );
           print unpack( ’%32i3’, $buf ), "\n";  # prints 123


           print unpack( ’%32A*’, "\x01\x10" ), "\n";  # prints 17

       Although the "%" code is documented as returning a "checksum": don’t
       bytes, they won’t guarantee a noticeable Hamming distance.

       put to good use to count set bits efficiently:

           my $bitcount = unpack( ’%32b*’, $mask );

       And an even parity bit can be determined like this:

           my $evenparity = unpack( ’%1b*’, $mask );


       Unicode is a character set that can represent most characters in most
       of the world’s languages, providing room for over one million different
       characters. Unicode 3.1 specifies 94,140 characters: The Basic Latin
       with characters that are used in several European languages is in the
       character sets from languages using non-Roman alphabets, interspersed
       or Braille.  (You might want to visit for a look at

       The Unicode character sets associates characters with integers. Encod-
       ing these numbers in an equal number of bytes would more than double
       the requirements for storing texts written in Latin alphabets.  The
       ones in three or more bytes.

       using template code "U". As an example, let’s produce the UTF-8 repre-
       sentation of the Euro currency symbol (code number 0x20AC):

          $UTF8{Euro} = pack( ’U’, 0x20AC );

       The round trip can be completed with "unpack":

          $Unicode{Euro} = unpack( ’U’, $UTF8{Euro} );

       Usually you’ll want to pack or unpack UTF-8 strings:

          # pack and unpack the Hebrew alphabet
          my $alefbet = pack( ’U*’, 0x05d0..0x05ea );
          my @hebrew = unpack( ’U*’, $utf );

       Another Portable Binary Encoding

       found at, the Scarab project.)  A BER (Binary Encoded Repre-
       sentation) compressed unsigned integer stores base 128 digits, most
       limit to BER encoding, but Perl won’t go to extremes.

          my $berbuf = pack( ’w*’, 1, 128, 128+1, 128*128+127 );

       "unpack" knows where to stop.

Template Grouping

       Prior to Perl 5.8, repetitions of templates had to be made by "x"-mul-
       tiplication of template strings. Now there is a better way as we may
       like this:

          unpack( ’v2 (vXXCC)5 v5’, $frame )

       Let’s explore this feature a little more. We’ll begin with the equiva-
       lent of

          join( ’’, map( substr( $_, 0, 1 ), @str ) )

       which returns a string consisting of the first character from each
       string.  Using pack, we can write

          pack( ’(A)’.@str, @str )


          pack( ’(A)*’, @str )



          $pd = pack( ’(CCS)*’, map( @$_, @dates ) );

       use several techniques. First, let’s use "x" and "X" to skip forward
       and back:

          $s = pack( ’(A)*’, unpack( ’(xAXXAx)*’, $s ) );

       where we were when the last "(" was encountered:

          $s = pack( ’(A)*’, unpack( ’(@1A @0A @2)*’, $s ) );

       Finally, there is also an entirely different approach by unpacking big
       endian shorts and packing them in the reverse byte order:

          $s = pack( ’(v)*’, unpack( ’(n)*’, $s );

Lengths and Widths

       String Lengths

       In the previous section we’ve seen a network message that was con-
       structed by prefixing the binary message length to the actual message.
       You’ll find that packing a length followed by so many bytes of data is
       a frequently used recipe since appending a null byte won’t work if a
       null byte may be part of the data. Here is an example where both tech-
       niques are used: after two null terminated strings with source and des-
       tination address, a Short Message (to a mobile phone) is sent after a
       length byte:

          my $msg = pack( ’Z*Z*CA*’, $src, $dst, length( $sm ), $sm );

       Unpacking this message can be done with the same template:

          ( $src, $dst, $len, $sm ) = unpack( ’Z*Z*CA*’, $msg );

       There’s a subtle trap lurking in the offing: Adding another field after
       cannot be unpacked naively:

          # pack a message
          my $msg = pack( ’Z*Z*CA*C’, $src, $dst, length( $sm ), $sm, $prio );

          # unpack fails - $prio remains undefined!
          ( $src, $dst, $len, $sm, $prio ) = unpack( ’Z*Z*CA*C’, $msg );

       undefined! Before we let disappointment dampen the morale: Perl’s got
       sleeve.  Watch this:

          my $msg = pack( ’Z* Z* C/A* C’, $src, $dst, $sm, $prio );

          # unpack
          ( $src, $dst, $sm, $prio ) = unpack( ’Z* Z* C/A* C’, $msg );

       Combining two pack codes with a slash ("/") associates them with a sin-
       gle value from the argument list. In "pack", the length of the argument
       is taken and packed according to the first code while the argument
       itself is added after being converted with the template code after the
       combination doesn’t make sense except when the second pack code isn’t
       "a*", "A*" or "Z*", Perl won’t let you.

       The pack code preceding "/" may be anything that’s fit to represent a
       "A4" or "Z*":

          # pack/unpack a string preceded by its length in ASCII
          my $buf = pack( ’A4/A*’, "Humpty-Dumpty" );
          # unpack $buf: ’13  Humpty-Dumpty’
          my $txt = unpack( ’A4/A*’, $buf );

       to work on older Perls you’ll need to "unpack( ’Z* Z* C’)" to get the

          my $msg = pack( ’Z* Z* C A* C’, $src, $dst, length $sm, $sm, $prio );

          # unpack
          ( undef, undef, $len) = unpack( ’Z* Z* C’, $msg );

       But that second "unpack" is rushing ahead. It isn’t using a simple lit-
       eral string for the template. So maybe we should introduce...

       Dynamic Templates

       So far, we’ve seen literals used as templates. If the list of pack
       items doesn’t have fixed length, an expression constructing the tem-
       Here’s an example: To store named string values in a way that can be
       followed by an additional delimiting null byte. Here’s how:

          my $env = pack( ’(A*A*Z*)’ . keys( %Env ) . ’C’,
                          map( { ( $_, ’=’, $Env{$_} ) } keys( %Env ) ), 0 );

       Let’s examine the cogs of this byte mill, one by one. There’s the "map"
       repeated according to the number of keys. (Yes, that’s what the "keys"
       tive readers may have noticed that we could have omitted the 0.)

       For the reverse operation, we’ll have to determine the number of items



       Counting Repetitions

       and up front we store the number of pairs:

          my $env = pack( ’S(S/A* S/A*)*’, scalar keys( %Env ), %Env );

       This simplifies the reverse operation as the number of repetitions can
       be unpacked with the "/" code:

          my %env = unpack( ’S/(S/A* S/A*)’, $env );

       template for "pack" and "unpack" because "pack" can’t determine a
       repeat count for a "()"-group.

Packing and Unpacking C Structures

       In previous sections we have seen how to pack numbers and character
       section right away with the terse remark that C structures don’t con-
       tain anything else, and therefore you already know all there is to it.
       Sorry, no: read on, please.

       The Alignment Pit

       In the consideration of speed against memory requirements the balance
       way C compilers allocate memory for structures: On architectures where
       a 16-bit or 32-bit operand can be moved faster between places in mem-
       ory, or to or from a CPU register, if it is aligned at an even or mul-
       give you this speed benefit by stuffing extra bytes into structures.
       If you don’t cross the C shoreline this is not likely to cause you any
       that, don’t you?)).

       To see how this affects "pack" and "unpack", we’ll compare these two C

          typedef struct {
            char     c1;
            short    s;
            char     c2;
            long     l;
          } gappy_t;

          typedef struct {
            long     l;
            short    s;
            char     c1;
            char     c2;
          } dense_t;

       requires only 8 bytes for a "dense_t". After investigating this fur-
       ther, we can draw memory maps, showing where the extra 4 bytes are hid-

          0           +4          +8          +12
          │c1│xx│  s  │c2│xx│xx│xx│     l     │    xx = fill byte

          0           +4          +8
          │     l     │  h  │c1│c2│

       And that’s where the first quirk strikes: "pack" and "unpack" templates

       The natural question: "Why can’t Perl compensate for the gaps?" war-
       rants an answer. One good reason is that C compilers might provide
       way structures are aligned, even at the level of an individual struc-
       ture field. And, if this were not enough, there is an insidious thing
       the alignment of the next item alone.

       OK, so let’s bite the bullet. Here’s one way to get the alignment right
       by inserting template codes "x", which don’t take a corresponding item
       from the list:

         my $gappy = pack( ’cxs cxxx l!’, $c1, $s, $c2, $l );

       Note the "!" after "l": We want to make sure that we pack a long inte-
       ger as it is compiled by our C compiler. And even now, it will only
       somebody somewhere has a platform where it doesn’t.  [Probably a Cray,

       Counting bytes and watching alignments in lengthy structures is bound
       to be a drag. Isn’t there a way we can create the template with a sim-
       ple program? Here’s a C program that does the trick:

          #include <stdio.h>
          #include <stddef.h>

          typedef struct {
            char     fc1;
            short    fs;
            char     fc2;
            long     fl;
          } gappy_t;

          #define Pt(struct,field,tchar) \

          int main() {
            Pt( gappy_t, fc1, c  );
            Pt( gappy_t, fs,  s! );
            Pt( gappy_t, fc2, c  );
            Pt( gappy_t, fl,  l! );
            printf( "\n" );


         my $gappy = pack( ’@0c @2s! @4c @8l!’, $c1, $s, $c2, $l );

       Gee, yet another template code - as if we hadn’t plenty. But "@" saves

       Neither using offsets nor adding "x"’s to bridge the gaps is satisfac-
       tory.  (Just imagine what happens if the structure changes.) What we
       next multiple of N".  In fluent Templatese, you say this with "x!N"
       where N is replaced by the appropriate value. Here’s the next version
       of our struct packaging:

         my $gappy = pack( ’c x!2 s c x!4 l!’, $c1, $s, $c2, $l );

       That’s certainly better, but we still have to know how long all the
       enclosing the appropriate pack code in brackets: "[s]". So, here’s the
       very best we can do:

         my $gappy = pack( ’c x![s] s c x![l!] l!’, $c1, $s, $c2, $l );

       Alignment, Take 2

       I’m afraid that we’re not quite through with the alignment catch yet.

          typedef struct {
            short    count;
            char     glyph;
          } cell_t;

          typedef cell_t buffer_t[BUFLEN];

       Where’s the catch? Padding is neither required before the first field
       "count", nor between this and the next field "glyph", so why can’t we
       simply pack like this:

          # something goes wrong here:
          pack( ’s!a’ x @buffer,

       required alignment of a structure or array is propagated to the next
       higher level where we have to consider padding at the end of each com-
       ponent as well. Thus the correct template is:

          pack( ’s!ax’ x @buffer,

       Alignment, Take 3


          typedef struct {
            char     foo[2];
          } foo_t;

       than any of its elements. [And if you think that this doesn’t affect

       Pointers for How to Use Them

       to call expects a, say, "void *" value, you cannot simply take a refer-
       ence to a Perl variable. (Although that value certainly is a memory
       address, it’s not the address where the variable’s contents are

       string".  Isn’t this what we want? Let’s try:

           # allocate some storage and pack a pointer to it
           my $memory = "\x00" x $size;
           my $memptr = pack( ’P’, $memory );

       But wait: doesn’t "pack" just return a sequence of bytes? How can we

           my $ptr = unpack( ’L!’, $memptr );



       this Perl function copying a file to standard output:

           require ’’;
           sub cat($){
               my $path = shift();
               my $size = -s $path;
               my $ptr = unpack( ’L’, pack( ’P’, $memory ) );
               open( F, $path ) ││ die( "$path: cannot open ($!)\n" );
               my $fd = fileno(F);
               print $memory;
               close( F );

       This is neither a specimen of simplicity nor a paragon of portability
       and access Perl’s otherwise well-guarded memory! (Important note:
       Perl’s "syscall" does not require you to construct pointers in this
       the address.)

       about to be unpacked: If it isn’t the null pointer (which will smartly
       it’s up to you to specify the actual size as an explicit length after

          my $mem = "abcdefghijklmn";
          print unpack( ’P5’, pack( ’P’, $mem ) ); # prints "abcde"



          my $buf = pack( ’p’, "abc\x00efhijklmn" );
          print unpack( ’p’, $buf );    # prints "abc"

       being implied by the string’s length, a number after pack code "p" is a
       repeat count, not a length as after "P".

       actually stored must be used with circumspection. Perl’s internal
       machinery considers the relation between a variable and that address as
       its very own private matter and doesn’t really care that we have
       obtained a copy. Therefore:

           that’s bound to go out of scope (and thereby freeing its memory)
           before you are done with using the memory at that address.

       ·   Be very careful with Perl operations that change the value of the
           variable. Appending something to the variable, for instance, might
           require reallocation of its storage, leaving you with a pointer
           into no-man’s land.

       ·   Don’t think that you can get the address of a Perl variable when it
           is stored as an integer or double number! "pack(’P’, $x)" will
           force the variable’s internal representation to string, just as if
           you had written something like "$x .= ’’".

       It’s safe, however, to P- or p-pack a string literal, because Perl sim-
       ply allocates an anonymous variable.

Pack Recipes

       and "unpack":

           # Convert IP address for socket functions

           unpack( ’%32b*’, $mask );

           # Determine the endianness of your system
           $is_little_endian = unpack( ’c’, pack( ’s’, 1 ) );
           $is_big_endian = unpack( ’xc’, pack( ’s’, 1 ) );

           # Determine the number of bits in a native integer
           $bits = unpack( ’%32I!’, ~0 );

           # Prepare argument for the nanosleep system call
           my $timespec = pack( ’L!L!’, $secs, $nanosecs );

       bytes to a line:

           my $i;
                      unpack( ’H2’ x length( $mem ), $mem ) ),
                 length( $mem ) % 16 ? "\n" : ’’;

Funnies Section

           # Pulling digits out of nowhere...
           print unpack( ’C’, pack( ’x’ ) ),
                 unpack( ’%B*’, pack( ’A’ ) ),
                 unpack( ’H’, pack( ’A’ ) ),
                 unpack( ’A’, unpack( ’C’, pack( ’A’ ) ) ), "\n";

           # One for the road ;-)
           my $advice = pack( ’all u can in a van’ );


       Simon Cozens and Wolfgang Laun.

perl v5.8.6                       2004-11-05                    PERLPACKTUT(1)

Man(1) output converted with man2html