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


We're (my Perl script and I) reading binary data from a dBase file. One piece of data is a 4-byte string, which may contain trailing zero bytes: 4A 04 00 00, say, or F6 00 00 00.

I want to remove the trailing zeros, if there are any. I was thinking a regexp would be the prime tool (especially seeing as I'm a regexp idiot at this point, and want to improve).

I tried s/(\x[01-FF]+)\x00/$1/ as something of a stab in the dark (can Perl even interpolate a range of hex values?) - it didn't substitute anything; the hex string comes back unchanged.

What's wrong with my regexp? What regexp(s) would work? Am I foolish for even using a regexp?

Many thanks...

---
donfreenut

Replies are listed 'Best First'.
(tye)Re: How do I remove trailing zeros from a hex string?
by tye (Sage) on Apr 12, 2001 at 00:13 UTC

    \x[01-FF] matches "\x00" (the nul byte) followed by one of( "0", any of the characters between "1" and "F" [in ASCII order], or "F" ). [\x01-\xFF] would work, though others have given you better ways to do this (I just wanted to answer "What's wrong with my regexp?"). Since \x wasn't followed by hex digits, it got interpreted as \x00.

            - tye (but my friends call me "Tye")
Re: How do I remove trailing zeros from a hex string?
by suaveant (Parson) on Apr 11, 2001 at 22:46 UTC
    ummm... probably s/\x00+$//; would suit your needs... not sure though, since it is hex data that will take 1 or more nulls off the end($) of a string
                    - Ant
Re: How do I remove trailing zeros from a hex string?
by twerq (Deacon) on Apr 11, 2001 at 22:48 UTC
    A RegExp should be fine, depending on how many times you have to do this. I'm not sure if \0 will match your zeros, but give an expression like this a try:
    s/\0+$//;
    which will nuke all zeros at the end of a string

    twerq update -- looks like someone beat me to the punch :)