Search code examples
perlstderr

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


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, is there a way I can call the subroutine to do this? Or can I capture the output to a variable and then use warn? I'm fairly new to perl.


Solution

  • 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);