Well, for Safe::World I made a full redirection of STDOUT and STDERR, with the option to redirecto to another HANDLER, SUB or SCALAR.

I have striped this code from it:

## Redirecting to another IO: tie(*STDERR => 'Safe::World::stderr' , \*STDOUT ) ; ## Redirecting to a SUB: sub errors { print "ERR>> @_\n" ;} tie(*STDERR => 'Safe::World::stderr' , \&errors ) ; ## Redirecting to a scalar: my $stderr ; tie(*STDERR => 'Safe::World::stderr' , \$stderr ) ; print "REDIRECT << $stderr >>\n" ; package Safe::World::stderr ; sub print_stderr { my $this = shift ; my $stderr = $this->{STDERR} ; if ( ref($stderr) eq 'SCALAR' ) { $$stderr .= $_[0] ;} elsif ( ref($stderr) eq 'CODE' ) { &$stderr($_[0]) ;} else { print $stderr $_[0] ;} return 1 ; } sub TIEHANDLE { my $class = shift ; bless( { STDERR => $_[0] } , $class) ; } sub PRINT { my $this = shift ; $this->print_stderr( join("", (@_[0..$#_])) ) ; return 1 ; } sub PRINTF { &PRINT($_[0],sprintf($_[1],@_[2..$#_])) ;} sub READ {} sub READLINE {} sub GETC {} sub WRITE {} sub FILENO {} sub CLOSE {} sub DESTROY {}
Note that if you want to catch all the error messages, you also should set $SIG{__WARN__} and $SIG{__DIE__}:
$SIG{__WARN__} = \&print_stderr ; $SIG{__DIE__} = \&handle_die ;

Enjoy! ;-P

Graciliano M. P.
"Creativity is the expression of the liberty".


In reply to Re: How do I redirect STDERR to a subroutine? by gmpassos
in thread How do I redirect STDERR to a subroutine? by slloyd

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.