Question

I have short script test.pl

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

use Getopt::Std;

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

I need to suppress Unknown option: messages generated by getopts and only get mine TRALALALALA on stderr.

Was it helpful?

Solution

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

Or you could even embed the "TRALALALALA" in the warn handler:

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

OTHER TIPS

You can also localize *::STDERR and open it to a buffer in a block like so:

@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';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top