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

ultranerds has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I'm trying to write a simple debug function, which will let me pass in a string + a color (or color combination). This is what I have so far:

sub print_debug { # black red green yellow blue magenta cyan white my ($text, $color) = @_; unless ($color) { print STDERR "$text \n"; } else { use Term::ANSIColor qw(:constants); if ($color =~ /blue/i) { print STDERR BLUE, "$text \n", RESET; } elsif ($color =~ /yellow/i) { print STDERR YELLOW, "$text \n", RESET; } elsif ($color =~ /red/i) { print STDERR RED, "$text \n", RESET; } elsif ($color =~ /blue/i) { print STDERR BLUE, "$text \n", RESET; } elsif ($color =~ /magenta/i) { print STDERR MAGENTA, "$text \n", RESET; } elsif ($color =~ /cyan/i) { print STDERR CYAN ON_GREEN, "$text \n", RESET; } } }
..which is called with:

print_debug ("foo","blue");

However, I would prefer to be able to simply pass in stuff like:

print_debug ("foo","blue on_white");

...which would convert to:

print BLUE ON_WHITE, "foo", RESET;

This doesn't seem to be valid syntax though:
sub print_debug { # black red green yellow blue magenta cyan white my ($text, $color) = @_; unless ($color) { print STDERR "$text \n"; } else { use Term::ANSIColor qw(:constants); print STDERR $color, "$text \n", RESET; } }
I'm guessing its cos the $color is actually a variable. Is there a way I can do this, or should I just stick with my other solution?

TIA

Andy

Replies are listed 'Best First'.
Re: Term::ANSIColor - possible to pass color as variable?
by eff_i_g (Curate) on Apr 13, 2011 at 13:18 UTC
    How about this?
    use warnings; use strict; use Term::ANSIColor qw(:constants); sub print_debug { print STDERR @_, RESET; } print_debug(BLUE ON_WHITE, 'Test');
      Ah nice - that did the trick - thanks!

      Andy
Re: Term::ANSIColor - possible to pass color as variable?
by JavaFan (Canon) on Apr 13, 2011 at 13:28 UTC
    sub print_debug { use Term::ANSIColor qw(:constants); my ($text, @colors) = @_; print STDERR @colors, $text, RESET; } use Term::ANSIColor qw(:constants); print_debug ("foo", BLUE ON_WHITE);
    Or
    sub print_debug { my ($text, $color) = @_; use Term::ANSIColor; print STDERR colored([$color], $text), "\n"; } print_debug "bar", "yellow on_magenta";
      Thanks- the first one works perfectly :)
Re: Term::ANSIColor - possible to pass color as variable?
by thargas (Deacon) on Apr 14, 2011 at 14:11 UTC