The Data::Validate
module has a is_hex function for which the source looks like this:
sub is_hex {
my $self = shift if ref($_[0]);
my $value = shift;
return unless defined $value;
return if $value =~ /[^0-9a-f]/i;
$value = lc($value);
my $int = hex($value);
return unless (defined $int);
my $hex = sprintf "%x", $int;
return $hex if ($hex eq $value);
# handle zero stripping
if (my ($z) = $value =~ /^(0+)/) {
return "$z$hex" if ("$z$hex" eq $value);
}
return;
}
Note that this module does not support the '0x' hexadecimal syntax, so you would have to strip that off yourself.
use warnings;
use strict;
use Data::Validate qw(:math);
my @data = qw(1234 ABCD 0x1234 foo 0xABCD bar);
foreach my $val (@data) {
if (defined(is_hex($val))) {
print "$val\tis hex";
} else {
print "$val\tis not hex";
}
}
__END__
$ perl -l 629540.pl
1234 is hex
ABCD is hex
0x1234 is not hex
foo is not hex
0xABCD is not hex
bar is not hex
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|