Perl: 同时在屏幕和文件打印输出

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:41   1864   0

Perl 代码实现:

#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

open(LOG, '>', 'LOG_FILE') or die "Can't redirect stdout: $!";
open(CMD, 'ls |');
open(STDERR, '>&', STDOUT) or die "Can't redirect stderr: $!";
open(STDERR, '>', 'LOG_FILE') or die "Can't redirect stderr: $!";
print "LOG_FILE\n";
while (<CMD>) {
    &lprint ($_)
}

sub lprint {
      my ($line) = @_;
      print LOG $line;  
      print $line;
}

close(CMD) or die "close CMD failed: $!";

exit(1);

利用Perl的Tee模块:

#!/usr/bin/perl

use IO::Tee; 
$tee = IO::Tee->new(">> log.txt", \*STDOUT); 
print $tee "Log on ".scalar(localtime)."\n";
#!/usr/bin/perl

open (STDOUT, "| tee -ai log.txt");
print "Log on ".scalar(localtime)."\n";
close (STDOUT);





分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP