Search code examples
perlstderrcurses

Is it with Curses possible, to print to STDERR instead of STDOUT?


How could I print "Hello, World!\n" (using Curses) to STDERR instead of STDOUT?

#!/usr/bin/env perl
use warnings;
use 5.12.0;
use Curses;

initscr();

addstr( 10, 0, "Hello, World!\n" );
refresh();

sleep 3;
endwin();

Solution

  • Having never used curses, but presuming it would be an argument to initscr, I did man initscr, which gave:

    A program that outputs to more than one terminal should use the newterm routine for each terminal instead of initscr. [...]

    So you get something like:

    #!/usr/bin/env perl
    use strict;
    use warnings;
    use Curses;
    
    open(my $stderr_term_in, '<', '/dev/null') or die $!;
    
    my $stdout_scr = newterm($ENV{TERM}, \*STDOUT, \*STDIN);
    my $stderr_scr = newterm($ENV{TERM}, \*STDERR, $stderr_term_in);
    
    set_term($stdout_scr);
    addstr(10, 0, "Hello, STDOUT!\n");
    refresh();
    
    set_term($stderr_scr);
    addstr(10, 0, "Hello, STDERR!\n");
    refresh();
    
    set_term($stdout_scr);
    endwin();
    delscreen($stdout_scr);
    
    set_term($stderr_scr);
    endwin();
    delscreen($stderr_scr);