Monday, October 25, 2010

Temporarily closing STDERR in Perl

Someone asked me how to get rid of a STDERR message being printed from a Perl module as it was being annoying to the program that they were writing. But also what a pain that the module was writing the errors!

Anyway, the simple emulation of the module was to make it print to STDERR. Here's the module code (module called p.pm);

---------------- 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 null
open (STDERR, ">/dev/null") || 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;
# 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