我读取了一个二进制文件,并希望确保某些特定的字节具有特定的值。perl做这件事的最好方法是什么?
my $blob = File::Slurp::read_file( 'blob.bin', {binmode=>'raw'} );
substr( $blob, 4, 4 ) == #equals what?我想测试字节5-8是否等于0x32 0x32 0x00 0x04。我应该将substr与什么进行比较?
发布于 2021-10-17 15:39:24
substr( $blob, 4, 4 ) eq "\x32\x32\x00\x04"如果它是一个32位无符号数字,您可能更喜欢以下内容:
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(对于带符号的32位整数,请使用l而不是oaf L。)
在使用unpack时,甚至可以避免substr。
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 /sxhttps://stackoverflow.com/questions/69605530
复制相似问题