Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 4th, 2012  |  syntax: None  |  size: 0.71 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How can I test strings containing ANSI color codes for equivalence in Perl?
  2. sub simulate($) {
  3.     my ($s) = @_;
  4.     my $colour = 'black';
  5.     my $bold = 0;
  6.     my @output;
  7.  
  8.     while (length $s) {
  9.         if ($s =~ s/Ax1B[1m//) { $bold = 1; }
  10.         elsif ($s =~ s/Ax1B[22m//) { $bold = 0; }
  11.         elsif ($s =~ s/Ax1B[30m//) { $colour = 'black'; }
  12.         elsif ($s =~ s/Ax1B[31m//) { $colour = 'red'; }
  13.         # ...
  14.         else {   # Plain character to be output
  15.             s/A(.)//s;
  16.             push @output, [ $1, $colour, $bold ];
  17.         }
  18.     }
  19.  
  20.     return @output;
  21. }
  22.  
  23. # Example usage
  24. use Test::More;
  25. is_deeply(
  26.     simulate("Hi x1B[31x1B[1mthere!"),
  27.     simulate("Hi x1B[1x1B[31mthere!"),
  28.     "FTW!");