How can I check strings containing ANSI color codes for equivalence in Perl?

I am writing tests for a Perl module that does things with ANSI color codes. I would like to be able to test two lines with built-in ANSI color codes to see if they will produce the same result when printing. This is not a simple string equality test, since putting multiple codes in a different order can still give the same result. For example, the codes for bold and blue can be combined with either the first to get bold blue.

So, is there an easy way to check two lines with ANSI color codes for equivalent output?

+3
source share
1 answer

- , . (character, colour, boldness) ( , ), , . .

, :

sub simulate($) {
    my ($s) = @_;
    my $colour = 'black';
    my $bold = 0;
    my @output;

    while (length $s) {
        if ($s =~ s/\A\x1B\[1m//) { $bold = 1; }
        elsif ($s =~ s/\A\x1B\[22m//) { $bold = 0; }
        elsif ($s =~ s/\A\x1B\[30m//) { $colour = 'black'; }
        elsif ($s =~ s/\A\x1B\[31m//) { $colour = 'red'; }
        # ...
        else {   # Plain character to be output
            s/\A(.)//s;
            push @output, [ $1, $colour, $bold ];
        }
    }

    return @output;
}

# Example usage
use Test::More;
is_deeply(
    simulate("Hi \x1B[31\x1B[1mthere!"), 
    simulate("Hi \x1B[1\x1B[31mthere!"),
    "FTW!");
+3

Source: https://habr.com/ru/post/1786828/


All Articles