use strict;
use warnings;
(my $binStr = <<BIN) =~ s/\n//g;
\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00
The end of the world is neigh
\x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00
unless you use pack and unpack
BIN
open my $fIn, '<', \$binStr;
binmode $fIn;
print "Using unpack\n";
while (read($fIn, (my $rec), 48)) {
my ($fileLocL, undef, $fileSizeL, undef, $fileName) =
unpack('VVVVa32', $rec);
printf "Loc: %d, Size: %d, Name: '%s'\n", $fileLocL, $fileSizeL, $
+fileName;
}
seek $fIn, 0, 0;
print "Using bogus substitution code\n";
while (!eof $fIn) {
my ($fileLoc, $fileSize, $fileName);
read($fIn, $fileLoc, 0x08);
read($fIn, $fileSize, 0x08);
read($fIn, $fileName, 0x20);
$fileLoc =~ s/(.)/sprintf("%02x",ord($1))/eg;
$fileSize =~ s/(.)/sprintf("%02x",ord($1))/eg;
$fileName =~ s/\0+$//;
printf "Loc: %d, Size: %d, Name: '%s'\n", $fileLoc, $fileSize, $fi
+leName;
}
Prints:
Using unpack
Loc: 1, Size: 2, Name: 'The end of the world is neigh '
Loc: 3, Size: 4, Name: 'unless you use pack and unpack '
Using bogus substitution code
Loc: -1, Size: -1, Name: 'The end of the world is neigh '
Loc: -1, Size: -1, Name: 'unless you use pack and unpack '
Note that I was using a build of Perl that doesn't have support for the quad word pack/unpack specification so I used the "VAX" long (32 bit) V specification and ignored the high words (that's the undefs in the variable list).
Oh, and the trailing spaces on the two "file name" lines in the sample data are important. Don't lose them copying this test script!
Perl is the programming world's equivalent of English
|