我正在编写一些测试Test::More,并且我正在测试打印的功能之一STDERR.我想测试输出STDERR,但有点不确定如何做到这一点.我知道我很亲密.这有效:
use strict;
use warnings;
use feature qw(say);
close STDERR;
open STDERR, ">", \my $error_string;
say STDERR "This is my message";
say qq(The \$error_string is equal to "$error_string");
Run Code Online (Sandbox Code Playgroud)
打印出:
The $error_string is equal to "This is my message
"
Run Code Online (Sandbox Code Playgroud)
但是,我不想关闭STDERR.我只是想重复它.
我试过这个:
use strict;
use warnings;
use feature qw(say);
open my $error_fh, ">", my $error_string;
open STDERR, ">&", $error_fh;
say STDERR "This is my message";
close $error_fh;
say qq(The \$error_string is equal to "$error_string");
Run Code Online (Sandbox Code Playgroud)
但是,$error_string是空白.
我究竟做错了什么?
对我来说,open STDERR, ">&", $error_fh(连同open STDERR, ">&" . fileno($error_fh))不会返回真正的价值.我认为>&模式可能是dup系统调用的一个非常直接的语法糖,它不适用于伪文件句柄$error_fh.
本地化STDERR怎么样?
{
local *STDERR = *$error_fh;
say STDERR "something";
}
# STDERR restored
Run Code Online (Sandbox Code Playgroud)