How to convert Hex to RGB? (Perl)

How do I convert my hexifer colors (e.g. 0000FF, FF00FF) to an arithmetic RGB format (e.g. 0 0 1, 1 0 1)?

I want to implement a command for this in some of my perl scripts, but I don’t even know how to do it manually.

Can someone help me do this in perl or even show me how to do it manually so that I can come up with my own perl command?

+4
source share
2 answers

Assuming you are trying to match 00..FF 16 with real numbers 0..1,

my @rgb = map $_ / 255, unpack 'C*', pack 'H*', $rgb_hex; 

  • pack 'H*', changes "FF00FF" to "\xFF\x00\xFF" .
  • unpack 'C*', changes "\xFF\x00\xFF" to 0xFF, 0x00, 0xFF .
  • map $_ / 255, changes 0xFF, 0x00, 0xFF to 0xFF/255, 0x00/255, 0xFF/255
+9
source

There is already a CPAN module that does what you want: https://metacpan.org/pod/Color::Rgb

 use Color::Rgb; my $hex = '#0000FF'; my @rgb = $rgb->hex2rgb($hex); # returns list of 0, 0, 255 my $rgb_string = $rgb->hex2rgb($hex,','); # returns string '0,0,255' 

It can also move in another direction:

 my @rgb = (0, 0, 255); my $hex_string = $rgb->rgb2hex(@rgb); # returns '0000FF' 
+8
source

Source: https://habr.com/ru/post/1491000/


All Articles