Adonis
10-11-2004, 09:44 AM
I am looking for a way to convert the hex value of a color (as used in HTML) to RGB decimal values. I did find something, but that continuously says the values are out of range.
Is there someone here who knows how to do this in Perl? I've been looking for a long time now and cant seem to find any decent info.
AlexV
10-11-2004, 10:35 AM
Took me about 10 minutes:sub hextodec {
my $hex = shift;
my %dec = (a => 10, b => 11, c => 12, d => 13, e => 14, f => 15);
return 'R: ' . ((substr($hex,0,1) =~ /\d/ ? substr($hex,0,1) : $dec{lc substr($hex,0,1)}) * 16 + (substr($hex,1,1) =~ /\d/ ? substr($hex,1,1) : $dec{lc substr($hex,1,1)})) . ' G: ' . ((substr($hex,2,1) =~ /\d/ ? substr($hex,2,1) : $dec{lc substr($hex,2,1)}) * 16 + (substr($hex,3,1) =~ /\d/ ? substr($hex,3,1) : $dec{lc substr($hex,3,1)})) . ' B: ' . ((substr($hex,4,1) =~ /\d/ ? substr($hex,4,1) : $dec{lc substr($hex,4,1)}) * 16 + (substr($hex,5,1) =~ /\d/ ? substr($hex,5,1) : $dec{lc substr($hex,5,1)}));
}
SimplyDiff
10-11-2004, 01:43 PM
Took me a lot less time :)
sub hex2rgb
{
my $hex = shift;
return(hex(substr($hex,0,2)),hex(substr($hex,2,2)),hex(substr($hex,4,2)));
}
Should probably note usage:
my($red,$green,$blue) = hex2rgb('D49A24');
Adonis
10-11-2004, 06:42 PM
Wow that worked! I've only tried Simplydiff's code. Its small... even smaller than AlexV's code. The code I was trying earlier was like 50 lines long :eek:
Anyway it works, thanks :) Is there also a way to check the initial hex code to make sure people do not type in erroneous values (so.. only letters A-F and digits 0-9. I had a code snipped that was in the 50 or so line of code that I initially used:
if ($tbcol !=~ m/[A-F0-9]/) {
$output = "Hex input not in range";
} else {
your code
}
But somehow that always returns "Hex input not in range" no matter if it's correct hex code or not. So I think the checking code is not functioning like it should.
As you may have figured.. i'm not an experienced Perl programmer but trying to get there somehow, lol.
SimplyDiff
10-11-2004, 08:34 PM
if ($tbcol =~ /[^A-F0-9]/i) {
if $tbcol contains anything that is not A-F or 0-9 case insensitive, then not in range.
Adonis
10-11-2004, 09:07 PM
Hmm yea that worked... what was wrong in my code?
Thanks :)
edge100x
10-11-2004, 11:28 PM
Just for fun, you could use unpack, too ;).
sub hextodec {
my @un = unpack('a2a2a2',shift);
map $_ = hex($_), @un;
return @un;
}
Also I think you meant
if ($tbcol =~ /^#?[A-F0-9]{6}$/i) {
Instead. That would enforce it for the entire string, and allow a # at the beginning. It would also make sure the string is 6 digits long.
edge100x
10-12-2004, 03:25 AM
if ($tbcol !~ /^#?[A-F0-9]{6}$/i), rather.