簡體   English   中英

Perl:將STDOUT重定向到兩個文件

[英]Perl: Redirect STDOUT to two files

如何在我的Perl腳本中將STDOUT流重定向到兩個文件(重復項)? 目前我只是流入一個日志文件:

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

我需要改變什么? 謝謝。

您也可以使用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!

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

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

使用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

如果您使用的是類Unix系統,請使用tee實用程序。

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

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

要在程序中設置此復制,請從STDOUT到外部T形過程設置管道。 通過"|-" 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
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