2013-08-20 37 views
6

我正在使用Test::More寫一些測試,並且我正在測試的其中一個功能打印到STDERR。我想測試輸出到STDERR,但我有點不確定如何做到這一點。我知道我很接近。這工作:如何使用Test :: More測試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"); 

此打印出:

The $error_string is equal to "This is my message 
" 

不過,我並不想關閉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"); 

但是,$error_string是空白。

我在做什麼錯?

回答

6

對於我來說,open STDERR, ">&", $error_fh(連同open STDERR, ">&" . fileno($error_fh))不會返回真值。我認爲>&模式對於dup系統調用來說可能是一個相當直接的語法糖,它不適用於像$error_fh這樣的僞文件句柄。

本地化STDERR怎麼樣?

{ 
    local *STDERR = *$error_fh; 
    say STDERR "something"; 
} 
# STDERR restored 
+0

當。我以爲我使用autodie;'打開。當我添加它時,我在'./test.pl第11行'處使用模式'>&':'錯誤的文件描述符'得到'無法打開'GLOB(0x7fcb82829808)''。本地化STDERR應該做到這一點。 –

2
# perl -MPerlIO::tee -MData::Printer -e 'my $output; STDERR->push_layer(tee=> \$output); warn "Danger, Will Robinson!"; p($output);' 
Danger, Will Robinson! at -e line 1. 
"Danger, Will Robinson! at -e line 1. 
" 
相關問題