donfreenut has asked for the wisdom of the Perl Monks concerning the following question:


Venerable Monks:

I'm coding a script to read a dBase memo file. The file is organized into 512-byte chunks.

The first 4 bytes of the 512-byte chunk determine if the chunk is in use. If it is, the first 4 bytes will contain the byte string "FFh FFh 08h 00h"

I'm thinking I'll use an array slice of the chunk for the comparison. That's a valid approach, right? How else could I do this?

Also, how do I compare the values in the scalar (which are characters) to the hex values (or decimal values, whatever)? Do I just ord each value in the slice?

Thanks...

---
donfreenut

Replies are listed 'Best First'.
Re: Looking for a hexadecimal byte string in a scalar variable
by davorg (Chancellor) on Apr 04, 2001 at 20:16 UTC

    No need to use an array slice. You can do something like this:

    if ($chunk =~ /^\xff\xff\x08\x00/) { print "Chunk in use\n"; } else { print "Chunk not used\n"; }

    There's an example of doing similar things with PNG files in chapter 7 of Data Munging with Perl.

    update: Fair point. Anchor added.

    --
    <http://www.dave.org.uk>

    "Perl makes the fun jobs fun
    and the boring jobs bearable" - me

      You're going to need to use the '^' anchor, e.g.
      if ($chunk =~ /^\xff\xff\x08\x00/) { print "Chunk in use\n"; } else { print "Chunk not used\n"; }
      Otherwise, you'll get a match if that byte sequence is anywhere in the chunk, not just in the beginning.
Re: Looking for a hexadecimal byte string in a scalar variable
by arturo (Vicar) on Apr 04, 2001 at 20:17 UTC

    Question : comparison of what to what? I'm not sure I get it. My take is that you want to see whether the first four bytes of $string are the hex values you describe.

    Probably, what you want is to use pack on the array ('FF','FF','08','00') and compare the result to the first four bytes of that string, which you can extract with substr, to wit:

    my $signal = pack ('H4', qw(ff ff 08 00)); #stuff if ( substr($string, 0, 4) eq $signal ) { # it's in use }

    Note, the upper case H in the pack is significant, it says the high nybble goes first. Try it with a lower-case h if you're getting wacky results.

    Philosophy can be made out of anything. Or less -- Jerry A. Fodor