http://www.perlmonks.org?node_id=1197693

So, an XML file or web post lists a bunch of colour specs like; 0x1e93c6, 0xf2b827, 0xd6563c, 0x6a5c9e, 0x31a35f; and you want to see what they look like.

You could paste each one into a colour viewer, but I couldn't find any tool to take them all at once. The following code takes random text containing hex colour strings, and creates an HTML file of square colour swatches.

#!/usr/bin/perl -w # # hextoswatch.pl - Extract colour strings from random code or HTML. # Currently only looks for 0xRRGGBB and #RRGGBB. # # perl hextoswatch.pl < source.txt > swatch.html # # and then open swatch.html in a browser! # # Chars that make up a colour string: # my $hexRegex = '0-9a-zA-Z'; my $colRegex = "#x$hexRegex"; my @hexSs = (); while ( <STDIN> ) { chomp; my @words = split /[^$colRegex]/; push @hexSs, (grep /^(0x|#)[$hexRegex]{6}$/, @words); } map { s/^(0x|#)(......)/$2/ } @hexSs; #print "Content-type: text/html\n\n"; print "<HTML>\n\n"; print "<HEAD>\n"; print "<TITLE>Colour swatches from random text</TITLE>\n"; print "</HEAD>\n\n"; print "<BODY><TABLE BORDER=1>\n"; print "<TR>"; my $cell = 0; foreach my $hex ( @hexSs ) { print "<TD BGCOLOR='#$hex'>", "<FONT COLOR='white'>$hex</FONT><BR><BR>", "<FONT COLOR='black'>$hex</FONT></TD>"; if ( $cell++ gt 4 ) { $cell=0; print "</TR>\n</TR>" } } print "</TR></TABLE></BODY></HTML>\n";

Replies are listed 'Best First'.
Re: Colour/color sampler
by Athanasius (Chancellor) on Aug 20, 2017 at 14:00 UTC

    Hello Nige,

    Thanks for that, it looks useful.

    A few minor points:

    • Although your code is, in fact, strict-compliant, it would be better to make this explicit with use strict;
    • Since you’re not using the list returned by map, it would probably be clearer to use a for loop here:
      s/^(0x|#)(.{6})/$2/ for @hexSs;
    • The statement print "</TR>\n</TR>" is probably meant to be print "</TR>\n<TR>" (i.e. ending the last table row and beginning another)
    • When comparing numbers, use > rather than gt (which is for stringwise comparison)
    • Although the comparison is with 4, the logic actually prints 6 cells per row. I think the following is clearer:
      my $cell = 0; for my $hex (@hexSs) { print "<TD BGCOLOR='#$hex'>", "<FONT COLOR='white'>$hex</FONT><BR /><BR />", "<FONT COLOR='black'>$hex</FONT></TD>"; if (++$cell >= 6) { $cell = 0; print "</TR>\n<TR>"; } }

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: Colour/color sampler
by zentara (Archbishop) on Aug 20, 2017 at 11:45 UTC
    Simple, yet interesting. It reminds me stenography.

    I'm not really a human, but I play one on earth. ..... an animated JAPH