in reply to Validating Hex Numbers

That won't really validate the number.

Feed it any of these non-hex strings and they'll be validated.

qw[ afg fA lA rA 0X ]
and the list goes on.

You need to make sure the entire string consists of only those characters, and in order to do that, you need anchors (notice I use \z instead of $)

/^[\da-f]+\z/i
The other thing you might have to check is the length of the string (should be even, even though 'AFF' might be considered '0AFF', whatever).

update: thanks sauoq for tyepo catch ;)


MJD says you can't just make shit up and expect the computer to know what you mean, retardo!
** The Third rule of perl club is a statement of fact: pod is sexy.

Replies are listed 'Best First'.
Re: Re: Validating Hex Numbers
by seattlejohn (Deacon) on Jan 09, 2003 at 01:11 UTC
    I would definitely *not* check the length of the string if this is intended to be a general-purpose solution. A is a perfectly valid hex number, just as 8 is a valid decimal number.

    Of course, in computing contexts single-hex-digit numbers are unusual, but the poster didn't specify what the source or destination of this data is, so I wouldn't want to build in that assumption without additional information.

    One thing that the post implies but doesn't make explicit is that "number" really means "non-negative integer". If you want to be truly comprehensive, something like -A8F.C is a valid hex number (namely -2073.75 decimal), but not something most of us likely encounter on a regular basis.

            $perlmonks{seattlejohn} = 'John Clyman';