[Wellington-pm] Pack/unpack - nagging guilt

Grant McLean grant at mclean.net.nz
Wed Jun 22 02:37:55 PDT 2005


Moving swiftly on to topics more Perlish ...

I recently had a need to take a string like this:

  #FFFFCCCC3333

and turn it into a list of three integers:

  (65535, 52428, 13107)

Aha!  I thought this looks like a job for unpack.

I have long felt a nagging guilt that although pack/unpack look really
powerful and the golfers and obfuscators seem to use them to achieve
useful things in surprising ways, I've almost never used them.  Not only
that, every time I've thought I needed them I ended up using something
else.  Like this time.

In this case, I ended up using something like this:

  my @rgb = map { hex } "#FFFFCCCC3333" =~ /^#(....)(....)(....)/;


If I needed to turn an assortment of values into a densely packed
sequence of bytes (eg: for some sort of network protocol) then pack
would be the right tool for the job.

Conversely, if I had a densely packed sequence of bytes that I needed to
split out into an assortment of values then unpack would do the trick.

In this case, I again fell into the trap of thinking a hex string looked
like a densely packed sequence of bytes, when of course it's nothing of
the sort.  It's a string of ASCII characters representing a sequence of
bytes.  

Given this realisation, I eventually did come up with a solution that
used unpack.  For that to work of course, I needed to use pack first.
And to do that, I had to get rid of that pesky leading '#'.  By which
stage the regex/map/hex thing was starting to look like a picture of
clarity.

Anyone got any other imaginative solutions?  With or without unpack.

Cheers
Grant




More information about the Wellington-pm mailing list