Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: Confession of a Perl Hacker

by doug (Pilgrim)
on Jan 22, 2001 at 23:40 UTC ( #53573=note: print w/replies, xml ) Need Help??

in reply to Confession of a Perl Hacker

Hmm, I don't have any magical pointers to give you, but it seems that your problem is more of getting your mind wrapped around the problem than understanding the syntax.

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

typedef struct my_data { char c; int i; } MY_DATA;
if you wanted to write $letter and $integer into something that looked like that, you would use
my $packet = pack 'c xxx N', $letter, $integer;
Now you can just write $packet to your socket and it gets to the other side OK. When the server responds, simply use
my ($letter, $integer) = unpack 'c xxx N', $resp;
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).

- 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....

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://53573]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2022-08-12 05:27 GMT
Find Nodes?
    Voting Booth?

    No recent polls found