bichonfrise74 has asked for the wisdom of the Perl Monks concerning the following question:

I have a script which calls a subroutine in a module. There is a possibility that the subroutine would give some error message and I would like to capture the standard error and save it on a file.

Below is what I have done so far, but I'm not sure if I'm doing it correctly or is there a better way of doing it?

Below is my test module.
package test; use strict; sub Check_File { my $file = `ls -l /tmp/hello.txt > /tmp/result.txt`; } 1
And below is the script that would print the standard error when I call the Check_File subroutine from the test module. So, if the "/tmp/hello.txt" does not exists, then it will give a standard error output. This is what I want to capture and save in a file.
#!/usr/bin/perl use strict; use test; print "Start of print.\n"; open( STDERR, ">", "/tmp/error.txt" ) or die "Error: Cannot open file - $!"; test->Check_File(); close( STDERR ); print "End of print.\n";
Any comments are appreciated. Thanks.

Replies are listed 'Best First'.
Re: Saving Standard Error
by jrsimmon (Hermit) on Aug 06, 2009 at 18:59 UTC
    • Closing STDERR is a bad idea. Perhaps there is a situation where it is not, but I can't think of any.
    • If you had searched for an answer to your question, you might have found intersting nodes such as this one, this one, and this one.
      Can you explain why closing STDERR is a bad idea? I never knew that.
        use strict; use warnings; warn "My errors go to the console!"; open(STDERR, ">myErr.log") or die $!; warn "My errors are logged!"; close(STDERR); warn "My errors go...nowhere!";
Re: Saving Standard Error
by tokpela (Chaplain) on Aug 06, 2009 at 19:58 UTC

    Use something like the IPC::Run3 module for this.

    You can capture STDERR into a scalar reference.