Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Perl alternate between colors while printing to terminal?

Why doesn't the following script work?

use strict;
use warnings;

use Term::ANSIColor ':constants';
my @colors = ( BLUE, GREEN );
my $select;

my @data = 1 .. 10;
print { $colors[$select++ % @colors] } $_, "\n" for @data;

outputs:

Can't use string ("") as a symbol ref while "strict refs" in use at - line 9.

like image 573
Zaid Avatar asked Jan 18 '26 05:01

Zaid


1 Answers

You are using the print { $fh } @strings syntax (documented here). The thing in curly braces (which are actually optional in simple cases) is interpreted as a file handle. Here, you pass a string instead of the file handle object, so Perl looks for a global variable with the name of the string. Unfortunately, this string contains funky command sequences (which happen to be unprintable) instead of some usable variable name.

Solution: don't use that weird syntax, and just do

my $select = 0;
print $colors[$select++ % @colors], $_, "\n" for 1 .. 10;
like image 51
amon Avatar answered Jan 21 '26 02:01

amon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!