in reply to Re^2: Handling ANSI Escape Sequences for Printing to Curses
in thread Handling ANSI Escape Sequences for Printing to Curses


Expensive? How much text are you putting out to the screen before the "inefficiency" is noticeable? It's a little premature to be optimizing at this time.


But consider what you were doing with the code you posted. You want to attron a color pair each time you encounter a yellow escape sequence. That seems like quite a customized requirement.

You're using Curses and Term::ANSIColor, so you're leveraging a lot already = good for you! I did a cursory search and couldn't find any more helpful modules beyond those two.

I'd write formatted_text() using a dispatch hash. Also made the regex quantifier non-greedy:
my %esc2action = ( color('yellow') => sub { attron(COLOR_PAIR(1)) }, color('reset') => sub { attroff(COLOR_PAIR(1)) }, ); sub formatted_text { my ($win, $text) = @_; # tokenize text on escape sequences for my $token (split /(\e\[[^m]+?m)/, $text) { my $act = $esc2action{$token}; if ($act) { $act->(); } else { addstr($win, $token); } } }

Replies are listed 'Best First'.
Re^4: Handling ANSI Escape Sequences for Printing to Curses
by atancasis (Sexton) on Aug 01, 2010 at 05:14 UTC

    Yup, utilizing a dispatch table would definitely be the smart way to do it.

    Also, thanks for knocking some sense into me. :-) I guess what I'm trying to do may already be a bit too customized to my requirements anyway. For now, I'll stick to implementing the parser, which would hopefully not be too expensive considering the ncurses utility I'll be doing will be tailing massive amounts of data.

    Thanks!