https://stackoverflow.com/a/71683833
#!/usr/bin/perl
use warnings;
use strict;
print STDERR "STDERR is on.\n";
my ($stderr_fh, $err_msg_ref) = suppress_std_err();
print "STDERR is now off and error messages are being suppressed and s
+aved.\n";
print STDERR "I'm an error message.\n";
restore_std_err($stderr_fh);
print STDERR "STDERR is back on\n";
print "Errors reported while STDERR was off: $$err_msg_ref\n";
#Saves STDERR in filehandle then turns it off.
#Any error messages that occur while STDERR is off are stored for safe
+keeping.
sub suppress_std_err {
my $suppressed_std_error_messages;
open (my $saved_std_err_fh, ">&", STDERR);
close STDERR;
open (STDERR, ">", \$suppressed_std_error_messages);
return ($saved_std_err_fh, \$suppressed_std_error_messages);
}
#Restores STDERR from saved filehandle.
sub restore_std_err {
my $old_std_err_fh = shift;
close STDERR;
open (STDERR, ">&", $old_std_err_fh);
}