I read a binary file and want to make sure that some specific bytes have some specific value. What's the most perl way of doing this?
my $blob = File::Slurp::read_file( 'blob.bin', {binmode=>'raw'} );
substr( $blob, 4, 4 ) == #equals what?
I want to test if bytes 5-8 equal 0x32 0x32 0x00 0x04
. What should I compare the substr to?
CodePudding user response:
substr( $blob, 4, 4 ) eq "\x32\x32\x00\x04"
If it's a 32-bit unsigned number, you might prefer the following:
unpack( "N", substr( $blob, 4, 4 ) ) == 0x32320004 # Big endian
unpack( "L>", substr( $blob, 4, 4 ) ) == 0x32320004 # Big endian
unpack( "L<", substr( $blob, 4, 4 ) ) == 0x04003232 # Little endian
unpack( "L", substr( $blob, 4, 4 ) ) == ... # Native endian
(Use l
instead oaf L
for signed 32-bit ints.)
substr
can even be avoided when using unpack
.
unpack( "x4 N", $blob ) == 0x32320004
You could also use a regex match.
$blob =~ /^.{4}\x32\x32\x00\x04/s