ASPN ActiveState Programmer Network
  ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups | Web Services
SEARCH
advanced | search help

Reference
ActivePerl 5.10
Core Documentation
perl
perlintro
perltoc
perlreftut
perldsc
perllol
perlrequick
perlretut
perlboot
perltoot
perltooc
perlbot
perlstyle
perlcheat
perltrap
perldebtut
perlfaq
perlfaq1
perlfaq2
perlfaq3
perlfaq4
perlfaq5
perlfaq6
perlfaq7
perlfaq8
perlfaq9
perlsyn
perldata
perlop
perlsub
perlfunc
perlopentut
perlpacktut
perlpod
perlpodspec
perlrun
perldiag
perllexwarn
perldebug
perlvar
perlre
perlrebackslash
perlrecharclass
perlreref
perlref
perlform
perlobj
perltie
perldbmfilter
perlipc
perlfork
perlnumber
perlthrtut
perlothrtut
perlport
perllocale
perluniintro
perlunicode
perlunifaq
perlunitut
perlebcdic
perlsec
perlmod
perlmodlib
perlmodstyle
perlmodinstall
perlnewmod
perlpragma
perlutil
perlcompile
perlfilter
perlglossary
perlembed
perldebguts
perlxstut
perlxs
perlclib
perlguts
perlcall
perlreapi
perlreguts
perlapi
perlintern
perliol
perlapio
perlhack
perlbook
perlcommunity
perltodo
perldoc
perlhist
perldelta
perl5100delta
perl595delta
perl594delta
perl593delta
perl592delta
perl591delta
perl590delta
perl588delta
perl587delta
perl586delta
perl585delta
perl584delta
perl583delta
perl582delta
perl581delta
perl58delta
perl573delta
perl572delta
perl571delta
perl570delta
perl561delta
perl56delta
perl5005delta
perl5004delta
perlartistic
perlgpl
perlcn
perljp
perlko
perltw
perlaix
perlamiga
perlapollo
perlbeos
perlbs2000
perlce
perlcygwin
perldgux
perldos
perlepoc
perlfreebsd
perlhpux
perlhurd
perlirix
perllinux
perlmachten
perlmacos
perlmacosx
perlmint
perlmpeix
perlnetware
perlopenbsd
perlos2
perlos390
perlos400
perlplan9
perlqnx
perlriscos
perlsolaris
perlsymbian
perltru64
perluts
perlvmesa
perlvms
perlvos
perlwin32

MyASPN >> Reference >> ActivePerl 5.10 >> Core Documentation
ActivePerl 5.10 documentation

NAME

perlpacktut - tutorial on pack and unpack


DESCRIPTION

pack and unpack are two functions for transforming data according to a user-defined template, between the guarded way Perl stores values and some well-defined representation as might be required in the environment 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 stored. In C, for instance, you can take the address of some variable, and the sizeof operator tells you how many bytes are allocated to the variable. Using the address and the size, you may access the storage to your heart's content.

In Perl, you just can't access memory at random, but the structural and representational conversion provided by pack and unpack is an excellent alternative. The pack function converts values to a byte sequence containing representations according to a given specification, the so-called "template" argument. unpack is the reverse process, deriving some values from the contents of a string of bytes. (Be cautioned, 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 values in binary representation? One good reason is input and output accessing some file, a device, or a network connection, whereby this binary representation is either forced on you or will give you some benefit in processing. Another cause is passing data to some system call that is not available as a Perl function: syscall requires you to provide parameters stored in the way it happens in a C program. Even text processing (as shown in the next section) may be simplified with judicious usage of these two functions.

To see how (un)packing works, we'll start with a simple template code where the conversion is in low gear: between the contents of a byte sequence and a string of hexadecimal digits. Let's use unpack, since this is likely to remind you of a dump program, or some desperate last message unfortunate programs are wont to throw at you before they expire into the wild blue yonder. Assuming that the variable $mem holds 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 digits corresponding to a byte:

   41204d414e204120504c414e20412043414e414c2050414e414d41

What was in this chunk of memory? Numbers, characters, or a mixture of both? Assuming that we're on a computer where ASCII (or some similar) encoding is used: hexadecimal values in the range 0x40 - 0x5A indicate an uppercase letter, and 0x20 encodes a space. So we might assume it is a piece of text, which some are able to read like a tabloid; but others will have to get hold of an ASCII table and relive that firstgrader feeling. Not caring too much about which way to read this, we note that unpack with the template code H converts the contents of a sequence of bytes into the customary hexadecimal notation. Since "a sequence of" is a pretty vague indication of quantity, H has been defined to convert just a single hexadecimal digit unless it is followed by a repeat count. An asterisk for the repeat count means to use whatever remains.

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

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

Since we feed a list of ten 2-digit hexadecimal strings to pack, the pack template should contain ten pack codes. If this is run on a computer 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

How do we do it? You might think first to use split; however, since split collapses blank fields, you'll never know whether a record was income or expenditure. Oops. Well, you could always use substr:

    while (<>) { 
        my $date   = substr($_,  0, 11);
        my $desc   = substr($_, 12, 27);
        my $income = substr($_, 40,  7);
        my $expend = substr($_, 52,  7);
        ...
    }

It's not really a barrel of laughs, is it? In fact, it's worse than it may seem; the eagle-eyed may notice that the first field should only be 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 (<>) { 
        my($date, $desc, $income, $expend) = 
            m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|;
        ...
    }

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

Hey, isn't Perl supposed to make this sort of thing easy? Well, it does, if you use the right tools. pack and unpack are designed to help you out when dealing with fixed-width data like the above. Let's have a look at a solution with unpack:

    while (<>) { 
        my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_);
        ...
    }

That looks a bit nicer; but we've got to take apart that weird template. Where did I pull that out of?

OK, let's have a look at some of our data again; in fact, we'll include the headers, and a handy ruler so we can keep track of where we are.

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

From this, we can see that the date column stretches from column 1 to column 10 - ten characters wide. The pack-ese for "character" is A, and ten of them are A10. So if we just wanted to extract the dates, we could say this:

    my($date) = unpack("A10", $_);

OK, what's next? Between the date and the description is a blank column; we want to skip over that. The x template means "skip forward", so we want one of those. Next, we have another batch of characters, from 12 to 38. That's 27 more characters, hence A27. (Don't make the fencepost error - there are 27 characters between 12 and 38, not 26. Count 'em!)

Now we skip another character and pick up the next 7 characters:

    my($date,$description,$income) = unpack("A10xA27xA7", $_);

Now comes the clever bit. Lines in our ledger which are just income and 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 remaining".

  • 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:

    my($date,$description,$income,$expend) = unpack("A10xA27xA7xA*", $_);

Now, that's our data parsed. I suppose what we might want to do now is total up our income and expenditure, and add another line to the end of our ledger - in the same format - saying how much we've brought in and how much we've spent:

    while (<>) {
        my($date, $desc, $income, $expend) = unpack("A10xA27xA7xA*", $_);
        $tot_income += $income;
        $tot_expend += $expend;
    }
    $tot_income = sprintf("%.2f", $tot_income); # Get them into 
    $tot_expend = sprintf("%.2f", $tot_expend); # "financial" format
    $date = POSIX::strftime("%m/%d/%Y", localtime);
    # OK, let's go:
    print pack("A10xA27xA7xA*", $date, "Totals", $tot_income, $tot_expend);

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 the perlfunc manpage says:

    x   A null byte.

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

What we actually need to do is expand the width of the fields. The A format pads any non-existent characters with spaces, so we can use the additional spaces to line up our fields, like this:

    print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);

(Note that you can put spaces in the template to make it more readable, 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: unfortunately, we can't get pack to right-justify our fields, but we can get sprintf to do it:

    $tot_income = sprintf("%.2f", $tot_income); 
    $tot_expend = sprintf("%12.2f", $tot_expend);
    $date = POSIX::strftime("%m/%d/%Y", localtime); 
    print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);

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 version; use unpack to turn a fixed-width-format string into several pieces of data.

  • The pack format A means "any character"; if you're packing and you've run out of things to pack, pack will fill the rest up with spaces.

  • x means "skip a byte" when unpacking; when packing, it means "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 should be affected by that format: A12 means "take 12 characters"; x6 means "skip 6 bytes" or "character 0, 6 times".

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

    Warning: when packing multiple pieces of data, * only means "consume all of the current piece of data". That's to say

        pack("A*A*", $one, $two)

    packs all of $one into the first A* and then all of $two into the second. This is a general principle: each format character corresponds to one piece of data to be packed.


Packing Numbers

So much for textual data. Let's get onto the meaty stuff that pack and unpack are best at: handling binary formats for numbers. There is, of course, not just one binary format - life would be too simple - but Perl will do all the finicky labor for you.

Integers

Packing and unpacking numbers implies conversion to and from some specific 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 number,

  • the byte ordering: whether the first byte is the least or most significant byte (or: little-endian or big-endian, respectively).

So, for instance, to pack 20302 to a signed 16 bit integer in your computer's representation you write

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

Again, the result is a string, now containing 2 bytes. If you print this string (which is, generally, not recommended) you might see ON or NO (depending on your system's byte ordering) - or something entirely different if your computer doesn't use ASCII character encoding. Unpacking $ps with the same template returns the original integer value:

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

This is true for all numeric template codes. But don't expect miracles: if the packed value exceeds the allotted byte capacity, high order bits are silently discarded, and unpack certainly won't be able to pull them back out of some magic hat. And, when you pack using a signed template code such as s, an excess value may result in the sign bit getting 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 for signed and unsigned 32-bit integers. And if this is not enough and your system supports 64 bit integers you can push the limits much closer to infinity with pack codes q and Q. A notable exception is provided by pack codes i and I for signed and unsigned integers of the "local custom" variety: Such an integer will take up as many bytes as a local C compiler returns for sizeof(int), but it'll use at least 32 bits.

Each of the integer pack codes sSlLqQ results in a fixed number of bytes, no matter where you execute your program. This may be useful for some applications, but it does not provide for a portable way to pass data structures between Perl and C programs (bound to happen when you call XS extensions or the Perl function syscall), or when you read or write binary files.