简体   繁体   English

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

[英]Perl: Redirect STDOUT to two files

How can I redirect the STDOUT stream to two files (duplicates) within my Perl script? 如何在我的Perl脚本中将STDOUT流重定向到两个文件(重复项)? Currently I am just streaming into a single log file: 目前我只是流入一个日志文件:

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

What do I have to change? 我需要改变什么? Thx. 谢谢。

You can also use IO::Tee . 您也可以使用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"

And yes, the output works: 是的,输出有效:

> cat tee1
Hey!
> cat tee2
Hey!

File::Tee provides the functionality you need. File :: Tee提供您所需的功能。

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

Use the tee PerlIO layer. 使用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

If you're using a Unix-like system, use the tee utility. 如果您使用的是类Unix系统,请使用tee实用程序。

$ perl -le 'print "Hello, world"' | tee /tmp/foo /tmp/bar
Hello, world

$ cat /tmp/foo /tmp/bar
Hello, world
Hello, world

To set up this duplication from within your program, set up a pipe from your STDOUT to an external tee process. 要在程序中设置此复制,请从STDOUT到外部T形过程设置管道。 Passing "|-" to open makes this easy to do. 通过"|-" 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: $!";

Demo: 演示:

$ ./stdout-copies-demo
Hello, world!

$ cat /tmp/foo /tmp/bar
Hello, world!
Hello, world!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM