Monday, October 25, 2010

Perl writing STDERR to a variable

Further to the problem of preventing STDERR from being displayed we wanted to capture the error message in a variable.

---------------- p.pm ---------------------------
package p;

sub dothis
{
print STDERR "There's a problem";
return 2;
}

1;
---------------- p.pm ---------------------------


The program code that temporarily prevents the STDERR from being displayed is as follows;

---------------- stopstderr ---------------------------
#!/usr/bin/perl
# using perl 5.8

use p;

# Open a new file handle to remember where STDERR really points to
open (OLDER, ">&", \*STDERR) || die "Can't dup stderr";
close STDERR;
# Repoint STDERR to a memory location so that we can capture the error message
open (STDERR, ">", \$var) || die "Can't remap STDERR";
print "No message here: ";
# No message printed from the module
my $s=p->dothis();
print "\n";
print "Return value is $s\n";
print "Trying to print to STDERR directly: ";
# No output printed to STDERR so next line goes to /dev/null
print STDERR "Can you see this?\n";
print "\n";
close STDERR;
# Let's print our the message captured in the variable $var even though we closed STDERR
print "The captured error message: $var\n";
# Repoint STDERR to where it normally goes
open (STDERR, ">&", \*OLDER) || die "Can't repoint STDERR";
close OLDER;
# Ensure that everything prints out when expected
select STDERR; $| = 1;
select STDOUT; $| = 1;
# Everything is happy again
print "Now STDERR is back, message here: ";
print STDERR "Cool :-)\n";

---------------- stopstderr ---------------------------


What fun :-)

No comments:

Post a Comment