#!/usr/bin/perl -w use strict; # text_tone( $text, $start_color, $end_color ) # # Takes a string $text and tones it from $start_color to $end_color, # adding tags around each character. Returns the toned string. # # Known "bug": Does not handle special characters such as ö or ÿ # Should be easy to add though. # sub text_tone { my ( $text, $start_color, $end_color ) = @_; # Regexp to match and capture a 6-digit hex string, # with our without a leading '#'. my $hex = qr/[0-9a-fA-F]/; my $match = qr/^#?($hex{2})($hex{2})($hex{2})$/; # Split $start- and $end_color into Red, Green and Blue, # at the same time check so they are valid, in this case, # exactly six hexadecimal numbers with a possible leading '#'. # $start_colors and $end_colors will hold one "byte" big parts, # that is R, G and B. # If a match fails, simply returns the original text. Can # easily be changed into a warning/error. my ( @start_colors ) = $start_color =~ /$match/ or return $text; my ( @end_colors ) = $end_color =~ /$match/ or return $text; my ( @steps ); # Convert hex values into decimal, for easier calculations. # Compute how big steps there will be between the colors. for( 0..2 ) { $start_colors[$_] = hex( $start_colors[$_] ); $steps[$_] = ( hex( $end_colors[$_] ) - $start_colors[$_] ) / ( length( $text ) -1 ); } # This will be our finished "rainbox" text. my $rainbow = ""; # We loop through all the characters, wrapping them in tags # to create the toning effect. foreach ( split( //, $text ) ) { # Don't waste our time with white space. # Will only produce empty font tags. if( /\s/ ) { $rainbow .= $_; } else { # Put together a hex string from the current permuation of colors. # We say that we want 2 hex numbers, and pad with zero if too small, # otherwise it will be just one digit sometimes, or padded with space. my $current_color = sprintf( "%02x%02x%02x", @start_colors ); # Create the tag with the character and color. $rainbow .= '' . $_ . ''; } # Step through the colors. for( 0..2 ) { $start_colors[$_] += $steps[$_]; } } # return the resulting rainbow string. :) return $rainbow; } #### print &text_tone( "Dog and Pony tries to learn some perl.", "#009966", "#cc3333" );