Hi everyone,
I have a question about using pack/unpack. I am packing a structure using the
following code (It will be at the end of the mail). I am basically packing the
following template: "A2A50la*"
within the a* is all the data that I read from $file1, after reading this data I want
to pack a 2 byte trailer. I can pack it with no problem, but when I try to unpack the
data I tried unpacking using to unpack statements and it failed. I want to do
something like this.
($header, $path, $length, $rest) = unpack "A2A50la*", $packedStuff;
($data,$trailer) = unpack "a$lengthA2", $rest;
You see I need $length to know how much data there is, I already know the trailer is
2bytes. When I try this unpacking twice, I don't get anything, but when I print out
$rest, I see that its still binary format so it should be unpackable. If I don't add
a 2 byte trailer then everything is fine, but I would like to figure out how to add a
trailer, and then unpack the binary packet like above.
Any ideas are greatly appreciated. Below is the code I have now, it doesn't have the
lines where I am unpacking twice. I took them out. Right now I am not putting a
2byte trailer in the packet.
Thanks in advance.
#!/usr/local/bin/perl
$file1 = "/opt/odigo/bin/classes/groups_4.1.0.0r.jar";
$file2 = "/tmp/grouptest.jar";
open(FROM,"$file1");
$blksize = (stat FROM)[11] || 84000;
$packedPath .= pack "A2A50", "HB", $file2;
#print "PACKED: $packedPath\n";
while ($len = sysread FROM, $buf, $blksize) {
if (!defined $len) {
next if $! == EINTR;
die "System read error: $!\n";
}
print "LEN: $len\n";
$real_length += $len;
$lbuf += length $buf;
$rbuf .= $buf;
}
print "RLEN: $real_length\n";
print "RBLEN: $lbuf\n";
$packedPath .= pack "l", $real_length;
$packedPath .= pack "a*", $rbuf;
#$packedPath .= pack "A2", "HF";
($header,$path,$llength,$data) = unpack "A2A50la*", $packedPath;
print "HEADER: $header\n";
print "PATH: $path\n";
print "LENGTH: $llength\n";
#print "TRAIL: $trailer\n";
exit 0;
open(TO,">$file2");
$offset = 0;
$ld = length $data;
print "LD: $ld\n";
while ($length) {
print "L: $length\n";
$written = syswrite TO, $data, $length, $offset;
print "W: $written\n";
print "O: $offset\n";
die "System write error: $!\n" unless defined $written;
$offset += $written;
print "O: $offset\n";
$length -= $written;
}