【问题标题】:How can I suppress warning messages emitted by Getopt::Std::getopts?如何抑制 Getopt::Std::getopts 发出的警告消息?
【发布时间】:2013-03-01 20:29:13
【问题描述】:

我有简短的脚本 test.pl

#!/usr/bin/perl
use locale;
use encoding 'utf-8';

use Getopt::Std;

getopts("dei") or print STDERR "TRALALALALA\n"; 
print"@ARGV\n";

我需要抑制由 getopts 生成的Unknown option: 消息,并且只在 stderr 上获取我的 TRALALALALA。

【问题讨论】:

  • 从读取 getopts 源代码中,如果不覆盖 CORE::warn 或安装警告处理程序,这是不可能的

标签: perl silent getopts


【解决方案1】:
{
    local $SIG{__WARN__} = sub { };  # Supress warnings
    getopts("dei")
        or print STDERR "TRALALALALA\n";
}

或者您甚至可以在警告处理程序中嵌入“TRALALALALA”:

{
    local $SIG{__WARN__} = sub { print STDERR "TRALALALALA\n" };
    getopts("dei");
}

【讨论】:

    【解决方案2】:

    您还可以本地化*::STDERR 并将其打开到块中的缓冲区,如下所示:

    @ARGV = qw(-i -a -g);
    {   open( local *STDERR, '>', \(my $stderr)) 
            or warn( 'Could not open to string!' )
            ;
        getopts( 'ig' );
        say '$stderr=' . $stderr;
    }
    
    print STDERR 'STDERR => out';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 2012-02-09
      • 1970-01-01
      相关资源
      最近更新 更多