我读取了一个二进制文件,并想确保某些特定字节具有特定值。做到这一点的最perl方法是什么?
my $blob = File::Slurp::read_file( 'blob.bin', {binmode=>'raw'} );
substr( $blob, 4, 4 ) == #equals what?
我想测试字节5-8是否等于
0x32 0x32 0x00 0x04
。我应该将 substr 与什么进行比较?
substr( $blob, 4, 4 ) eq "\x32\x32\x00\x04"
如果是 32 位无符号数,您可能更喜欢以下内容:
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
unpack( "N", substr( $blob, 4, 4 ) ) == 0x32320004 # Big endian
unpack( "V", substr( $blob, 4, 4 ) ) == 0x04003232 # Little endian
(对于带符号的 32 位整数,请使用
l
代替 oaf L
。)
使用substr
时甚至可以避免
unpack
。
unpack( "x4 N", $blob ) == 0x32320004
您还可以使用正则表达式匹配。
$blob =~ /^.{4}\x32\x32\x00\x04/s
$blob =~ /^ .{4} \x32\x32\x00\x04 /sx
my $packed = pack( "N", 0x32320004 );
$blob =~ /^ .{4} \Q$packed\E /sx