Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

capture STDERR from within code?

by leocharre (Priest)
on Nov 09, 2009 at 15:53 UTC ( [id://805950]=perlquestion: print w/replies, xml ) Need Help??

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

I have a kinda silly question.. I have some code that possibly outputs to STDERR, how can I check what's in there, if anything?
bar(); sub bar { (print STDERR "miscellanea") if ( (int rand(10) > 5 ); 1; }

I can think of running it and sending to a file via the shell.. perl x 2> out and then I can look at out, but.. that seems extreme. ..

Replies are listed 'Best First'.
Re: capture STDERR from within code?
by BioLion (Curate) on Nov 09, 2009 at 16:01 UTC
Re: capture STDERR from within code?
by kennethk (Abbot) on Nov 09, 2009 at 16:01 UTC
      close(STDERR); open(STDERR, '>', \my $BUF) or die $!; warn "hey there"; $BUF=~/hey there/ or die;
      Yes! You rawk, thank you.
Re: capture STDERR from within code?
by ack (Deacon) on Nov 09, 2009 at 16:12 UTC

    I'm not sure I understand the your question.

    Are you wanting to be able, from within your code, to see what has been output to STDERR?

    If so, then the reply from kennethk is an excellent place to start.

    My only caution is that if you map SDTERR to a variable and then have several places where output might go to STDERR, then each successive write to STDERR will overwrite the variable. So you'll need to check it after every possible STDERR write.

    Alternativly, you could consider trapping the error using an eval() construct where you can write your own simple error handler that would perhaps output successive messages to an array which you can then check at your leizure.

    On the other hand, if you simply want to see when or if an error message is being written properly, then there are other possibilities.

    For instance, if you're running from the Command Line then STDERR is automatically mapped to STDOUT and the messages are written to the console. The only challenge, at least for me, is that there is no particular distinguishing markings that tell you whether STDERR or STDOUT is being written. In that instance, I usually pre-pend something like 'STDERR:' to the message (in the OP's case it would be, for example, 'STDERR: miscellaneous') so that I can easily pick out the STDOUT from the STDERR messages.

    ack Albuquerque, NM

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://805950]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-04-26 00:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found