Perl:将STDOUT重定向到两个文件

12

我该如何在Perl脚本中将STDOUT流重定向到两个文件(副本)中?目前我只是将其流式传输到单个日志文件中:

open(STDOUT, ">$out_file") or die "Can't open $out_file: $!\n";

我需要做哪些更改?谢谢。

4个回答

10
您还可以使用IO::Tee
use strict;
use warnings;
use IO::Tee;

open(my $fh1,">","tee1") or die $!;
open(my $fh2,">","tee2") or die $!;

my $tee=IO::Tee->new($fh1,$fh2);

select $tee; #This makes $tee the default handle.

print "Hey!\n"; #Because of the select, you don't have to do print $tee "Hey!\n"

是的,输出结果正常:

> cat tee1
Hey!
> cat tee2
Hey!

OP在哪里要求替换STDOUT(...用什么替换?0_o)。OP想要“将STDOUT流重定向到两个文件”。 - user554546
通过 select 选择 $tee$tee 将成为默认句柄。TIMTOWTDI,无论您喜不喜欢。 - user554546
我真的真的很糊涂。删除我完全错误的评论! - ikegami
->new($fh1,$fh2) 应该改为 ->new($fh1,\*STDOUT) - ikegami
2
注意:如果有人直接引用STDOUT或调用“system”,那么这将无法正常工作。 - ikegami

4

File::Tee 提供了您所需的功能。

use File::Tee qw( tee );
tee(STDOUT, '>', 'stdout.txt');

4

使用tee PerlIO层。

use PerlIO::Util;
*STDOUT->push_layer(tee => "/tmp/bar");
print "data\n";

$ perl tee_script.pl > /tmp/foo
$ cat /tmp/foo
data
$ cat /tmp/bar
data

3
如果您使用的是类Unix系统,请使用tee实用程序。
$ perl -le 'print "Hello, world"' | tee /tmp/foo /tmp/bar
Hello, world

$ cat /tmp/foo /tmp/bar
Hello, world
Hello, world
为了在程序内设置这种复制,需要将STDOUT与外部的tee进程建立一个管道。通过向open传递"|-"来轻松完成此操作。
#! /usr/bin/env perl

use strict;
use warnings;

my @copies = qw( /tmp/foo /tmp/bar );

open STDOUT, "|-", "tee", @copies or die "$0: tee failed: $!";

print "Hello, world!\n";

close STDOUT or warn "$0: close: $!";

演示:

$ ./stdout-copies-demo
你好,世界!

$ cat /tmp/foo /tmp/bar
你好,世界!
你好,世界!

仅两个文件(无屏幕):perl ... | tell /tmp/foo > /tmp/bar - ikegami
我想在脚本内部进行重定向。目前我只有一个日志文件:open(STDOUT, ">$out_file") or die "无法打开 $out_file: $!\n";我需要改变什么? - Matthias Munz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接