Temporarily Redirect STDOUT to /dev/null - Not Working All The Time

buffer, perl, printing

Solution

I need to explicitly store and restore. It works for my case. But I am not sure why.

# Take copies of the file descriptors
open OLDOUT, '>&STDOUT';
my $returned_values = 0;
{
    # Our mighty holy legacy code love to print out message in the middle of operation. Shihh....
    # Let's quietly redirect those message to /dev/null.
    local *STDOUT;
    open STDOUT, '>/dev/null' or warn "Can't open /dev/null: $!";
    print "BYE BYE WORLD";    # Shouldn't show in webpage.
    close STDOUT;
}
# Restore stdout.
open STDOUT, '>&OLDOUT' or die "Can't restore stdout: $!";
# Avoid leaks by closing the independent copies.
close OLDOUT or die "Can't close OLDOUT: $!";

Problem

I am using ``` Server version: Apache/1.3.34 (Debian) mod_perl - 1.29 ``` By refering to STDIN, STDOUT, and STDERR Streams ``` #!/usr/bin/perl5 package main; use strict 'vars'; { # Our mighty holy legacy code love to print out message in the middle of operation. Shihh.... # Let's quietly redirect those message to /dev/null. my $nullfh = Apache::gensym( ); open $nullfh, '>/dev/null' or warn "Can't open /dev/null: $!"; local *STDOUT = $nullfh; print "BYE BYE WORLD"; # Shouldn't show in webpage. close $nullfh; } print "X BEGIN HELLO WORLD"; # Should show in webpage. ``` I realize that it is not working all the time. For example, I refresh the page for 10 times. x times it will print out "X BEGIN HELLO WORLD". (10-x) time it just print out nothing. I cannot find any reason why it behave this way. May I know anyone of you encounter similar problem as me?

Original source