Heres a quick sub I wrote to html colorize a text string. Its not exactly perfect, but works for my needs. Any improvements would be appreciated.
sub colorize { my $phrase = shift (@_) ; my @colors = ("#0033ff", "#0066ff", "#0099ff", "#00ccff", "#00ffff", "#66ffff", "#ccffff", "#ffffff", "#ccffff", "#66ffff", "#00ffff", "#00ccff", "#0099ff", "#0066ff", "#0033ff", "#0000ff"); my ($colorphrase,$length,$phraseparts,$xx,$each_char,$it) ; $length = length ($phrase) ; $phraseparts = ($length / ($#colors+1)) ; for ($xx=0;$xx<$length;$xx++) { $each_char = substr ($phrase,$xx,1); $it = int ($xx / $phraseparts); $colorphrase.= "<font color=$colors[$it]>$each_char</font>" ; } return $colorphrase; }

Replies are listed 'Best First'.
Re: Colorize
by marcink (Monk) on Jun 12, 2001 at 18:06 UTC
    1. you can use my $phrase=shift; instead of my $phrase = shift(@_); -- @_ is the default parameter in list context.

    2. in scalar context @colors == $#colors + 1

    3. the HTML you create contains one FONT tag per letter, but you don't need more than @colors of them. You could change the loop to get one pass per color instead of one pass per character.

    -mk
Re: Colorize
by extremely (Priest) on Jun 13, 2001 at 06:58 UTC
    Well, not to toot my own horn too much but you could add my Web Color Spectrum Generator to yours and let it scale a color spectrum across the text. That is one of the two uses I built it for, the other being coloring table rows.

    --
    $you = new YOU;
    honk() if $you->love(perl)

      I actaully looked at that, but deemed it too much for my needs.

      I am currently using this sub to colorize 1,000s of mp3 titles on a private mp3 jukebox of mine. Everytime time I generate the list(do a search) this sub gets called 1,000s of times. I wanted it to keep it light and tight so to speak. Just the basics. Get in and get out quick.

      WrongWay
        If speed is a concern, among other things, you might move the declaration of @colors out into an enclosing block:
        { my @colors=(...); sub colorize { ... } }
        This way, @colors will still have only be 'locally' visible to colorize, but it will only be created once, at load-time, instead of every time you call colorize();.
Re: Colorize
by planetscape (Chancellor) on Jul 16, 2005 at 16:45 UTC