Re: [問題] 請教如何實現下邊這種重定向﹖
※ 引述《herolee (hero)》之銘言:
: 1、首先希望把標準錯誤能夠重定向到標準輸出﹐類似shell的 2>&1
您可以使用 open STDERR, ">&STDOUT"
(請參考 http://perldoc.perl.org/functions/open.html )
: 2、希望能把所有標準輸出(已包含標準錯誤的內容)在屏幕打印的同時﹐
: 也輸出到某個文件中。
: 請問﹐上述功能用perl怎麼實現呢﹖我隻會bash下的辦法。。。
CPAN 上有一些 module 可以試試: File::Tee (不能在 Windows 上執行)、Tee、
IO::CaptureOutput 等
這些 module 都能將如 system() 的輸出也導到檔案 (跟 tee 的功能相同)
如果您只是想將 print、printf、syswrite 等輸出的結果同時導到檔案,而忽略
system() 等由子行程輸出的結果 (這可能需要透過 IPC)
則可以考慮使用 IO::Tee
您甚至可以自己利用 tie 實作一簡單的多工輸出的 file handle (事實上 IO::Tee 就是
用 tie 實作的)
Tee.pm 的內容為:
#!/usr/bin/perl
use warnings;
use strict;
package Tee;
sub TIEHANDLE {
my $class = shift;
my @fh = @_;
bless \@fh, $class;
}
sub WRITE {
my $this = shift;
syswrite $_, @_ for @$this;
}
sub PRINT {
my $this = shift;
print {$_} @_ for @$this;
}
sub PRINTF {
my $this = shift;
printf {$_} @_ for @$this;
}
1;
而主程式為:
#!/usr/bin/perl
use warnings;
use strict;
use Tee;
open my $log, '>', 'log.txt' or die;
tie *FH, 'Tee', \*STDOUT, $log;
select(*FH);
print "hello world!\n";
這時 "hello world!\n" 會同時輸出到 STDOUT 和檔案 log.txt
(請參考 http://perldoc.perl.org/perltie.html#Tying-FileHandles )
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 111.243.162.213
推
05/14 11:12, , 1F
05/14 11:12, 1F
→
05/14 16:31, , 2F
05/14 16:31, 2F
→
05/14 16:34, , 3F
05/14 16:34, 3F
推
05/14 23:22, , 4F
05/14 23:22, 4F
討論串 (同標題文章)
Perl 近期熱門文章
PTT數位生活區 即時熱門文章