perl – 暂时将STDOUT重定向到/ dev / null – 不能一直工作

前端之家收集整理的这篇文章主要介绍了perl – 暂时将STDOUT重定向到/ dev / null – 不能一直工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在用

Server version: Apache/1.3.34 (Debian)
mod_perl - 1.29

参考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.

我意识到它并不是一直都在工作.例如,我刷新页面10次. x次将打印出“X BEGIN HELLO WORLD”. (10-x)时间它只打印出来.

我找不到任何理由这样做的原因.我可以知道你们中的任何人遇到与我类似的问题吗?

解决方法

我需要明确存储和恢复.它适用于我的情况.但我不确定为什么.

# 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: $!";

猜你在找的Perl相关文章