I'm defining some tests for a library I'm using. One of my tests is calling the code in such a way that it produces warnings, which is expected. However, I'd ideally like to suppress these warnings during testing while allowing the library to continue emitting them during normal usage. It seems I may be misunderstanding the lexical nature of the warnings pragma.
I would expect the code below to disable the 'redundant' warning for all code called inside the block - instead, it produces a warning that I cannot seem to disable without editing the f function.
#!perl
use v5.36; # automatically enable strict and warnings
package WarningTest {
sub f {sprintf("%s", @_)}
};
{
no warnings qw(redundant);
say WarningTest::f(1, 2);
}
./tmp.pl
Redundant argument in sprintf at ./tmp.pl line 5.
1
Is there any way to actually disable warnings for the duration of a call to a remote library function?
One way would be to localize the WARN hook, which controls how the warnings are emitted.
# in a block where you want warnings not to go STDERR
local $SIG{__WARN__} = sub { say "Warning: @_" }; # now it won't go to STDERR stream
...
Also see %SIG entry in perlvar
The routine indicated by
$SIG{__WARN__}is called when a warning message is about to be printed. The warning message is passed as the first argument. The presence of a__WARN__hook causes the ordinary printing of warnings to STDERR to be suppressed.
I prefer to explicitly localize it with a block, and with an informative label, too
TESTING_f: {
local $SIG{__WARN__} = sub { say "Warning: @_" }; # not on STDERR stream
say WarningTest::f(1, 2);
};
# normal behavior restored
If this doesn't do it -- what is possible -- then try making warnings fatal and catching the exception.