Is there a way to capture a subroutine's print output to a variable so I can send it to stderr instead?

后端 未结 4 1043
离开以前
离开以前 2021-01-12 08:50

Suppose we have:

sub test {
        print \"testing\\n\";
}

If there is a case where I want to have it print to stderr instead of stdout, i

4条回答
  •  失恋的感觉
    2021-01-12 09:17

    Yes there is. print sends its output to the "selected" filehandle, which is usually STDOUT. But Perl provides the select function for you to change it.

    select(STDERR);
    &test;           # send output to STDERR
    select(STDOUT);  # restore default output handle
    

    The select function returns the previously selected filehandle, so you can capture it and restore it later.

    my $orig_select = select(STDERR);
    &test;
    select($orig_select);
    

提交回复
热议问题