in reply to Confession of a Perl Hacker
One way of thinking about pack/unpack is to think about copying data from Perl's format (large, but quickly accessed) to C's format (dense, but slower (for Perl at least)). Even if C isn't your goal, this generalizes to say that pack/unpack are good ways to convert to/from standard representations.
I used pack/unpack to communicate across TCP/IP with a rather crappy server that served structs in C. My perl had to prepare data that would mimic the data structures used in that C compiler. pack was the way to do it, and unpack() to understand what it replied.
A quick example would be
if you wanted to write $letter and $integer into something that looked like that, you would usetypedef struct my_data { char c; int i; } MY_DATA;
Now you can just write $packet to your socket and it gets to the other side OK. When the server responds, simply usemy $packet = pack 'c xxx N', $letter, $integer;
This shows the basics. Hopefully this helps. The problem you might be having is that some people use pack/unpack to do magic. If you want to play around with bits/bytes in an un-perl-like fashion this is how to do it (well, vec() helps too). Try to understand what they are doing before delving into how they are doing it (trite, I know).my ($letter, $integer) = unpack 'c xxx N', $resp;
- doug
PS: All those stupid 'x' pack/unpack fields are because most compilers add pad bytes to keep alignment regular. In every unix compiler I've looked at, sizeof(MY_DATA) would be 8, although only 5 bytes are actually needed.
PS #2: I'm doing this from memory, and I'm starting to get senile....