in reply to Is it possible to include colored text in formatted output using write

can you provide a Short, Self-Contained, Correct Example to show how you use format? I am uninitiated.

print with sprintf works fine for me:

use Term::ANSIColor qw (color colored colorstrip :constants); my $x = sprintf '%s XYZ', "Hello ".colored("there", "green")." and bye +."; print $x; print sprintf("123 %s 456 %s 789\n", colored("hello", "red").sprintf("abc %s xyz", colored("bye", "green") ), $x );

Dirty hack: re-escaping refreshing the ANSI escape sequence in The purpose of the [32mts [0m script... works for me with (the naive) =~ s/\[/\033[/g;

bw, bliako

Replies are listed 'Best First'.
Re^2: Is it possible to include colored text in formatted output using write
by 1nickt (Canon) on May 11, 2023 at 22:38 UTC

    Hi Bliako, this is what I used to repro the issue:

    use strict; use warnings; use Term::ANSIColor qw (color colored colorstrip :constants); my $str = "The purpose of the " . colored ("ts", "green") . " script i +s to ..."; print "$str\n"; format STDOUT = @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< $str . write;


    The way forward always starts with a minimal test.
Re^2: Is it possible to include colored text in formatted output using write
by fireblood (Scribe) on May 11, 2023 at 22:56 UTC

    Here is what I currently have. I'm defining the format in an eval instruction because later I plan to set the length of the field based on the width of the screen window, but at present it is as follows:

    my $format_definition_expression = "format one_field_format =\n" . "@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" . "\$one_field_text\n" . ".\n"; eval $format_definition_expression;

    Later on down I have:

    unless (open ($fh_more_pipe, "|-", "cat - | more")) { print "\nCould not open \$fh_more_pipe: $!\n\n"; die; } select $fh_more_pipe; $|++; $~ = "one_field_format"; my $one_field_text = "The purpose of the " . colored ($StdHdr::ThisScriptName, "green") . " script is to search for a specified character string " . "in all plain text files that reside in and below a " . "specified starting directory, optionally writing " . "the names of matching files to a specified save file." . "n\n"; write;

    I know that I will need to add double-tildes (~~) to the line in the format definition to make the text that I want to display to flow to as many subsequent lines as necessary to accommodate the entire text of the message, but for now I'm just focusing on getting the colored text elements to be properly rendered in just the first line before going on to that.

    Thanks for looking at this.