arraysstringcolorsraku

Unable to print color when color code is taken from array


I have color codes stored in an array. I cannot print color when I take a color code from the array, but I can print color if I use the code directly in a "say" or "print" statement. What can I do to debug? I have Rakudo v2025.06.1.

[0] >  my @allColors = '\e[48;5;1m  \e[48;5;2m  \e[48;5;3m  \e[48;5;4m  \e[48;5;5m'.words;
[\e[48;5;1m \e[48;5;2m \e[48;5;3m \e[48;5;4m \e[48;5;5m]
[1] > my $colorOff = "\e[0m";

[2] > say "@allColors[0] show color $colorOff";
\e[48;5;1m show color  # <<<============================= no color is shown here
[2] > say "\e[48;5;1m show color $colorOff";
 show color <<<========================================== intended color shown, red background
[2] > my $a = @allColors[0]
\e[48;5;1m
[3] > say "$a show color $colorOff"
\e[48;5;1m show color <<<================================ no color here either

How come a string is interpreted differently when it is taken from an array and when it is directly written? But then, how come $colorOff works okay?


Solution

  • The issue is with how the string is quoted.

    You wrote the array using single quotes:

    my @allColors = '\e[48;5;1m  \e[48;5;2m ...'.words;
    

    In single quotes, \e is not treated as an escape character — it’s just the literal characters \ and e. That’s why you only see \e[48;5;1m printed.

    When you use double quotes:

    my @allColors = "\e[48;5;1m  \e[48;5;2m ...".words;
    

    then \e is interpreted as the actual escape character, and the colors show up correctly.

    That’s also why $colorOff works — you defined it with double quotes.

    So the fix is: use double quotes for your color codes.