2012-05-09 4 views
12

STDOUT 스트림을 Perl 스크립트 내에서 두 개의 파일 (중복)로 리디렉션 할 수 있습니까? 현재 단일 로그 파일로 스트리밍 중입니다 :Perl : STDOUT을 두 파일로 리디렉션

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

무엇을 변경해야합니까? 고마워.

답변

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! 
+0

OP는 어디에서 "STDOUT"(... 그리고? 0_o)을 대체 할 것을 요구 했습니까? OP는 "STDOUT"스트림을 두 개의 파일로 리디렉션하려고했습니다. –

+0

'$ tee'를'select '하면'$ tee'가 기본 핸들이됩니다. TIMTOWTDI, 당신이 싫든 좋든. –

+0

나는 정말로 눈이 멀다. 내 compeltey 허위 의견을 삭제! – ikegami

3

유닉스 계열 시스템을 사용하는 경우 tee 유틸리티를 사용하십시오.

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

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

는 외부 과정에 STDOUT에서 파이프를 설정, 프로그램 내에서이 복제를 설정합니다. "|-"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!
+0

두 개의 파일 (화면 없음) : '... |/tmp/foo>/tmp/bar' – ikegami

+0

스크립트 안에서 리디렉션하고 싶습니다. 현재 하나의 로그 파일을 가지고 있습니다 : open (STDOUT, "> $ out_file") 또는 die "can not open $ out_file : $! \ n"; 무엇을 변경해야합니까? –

+0

@Matze 업데이트 된 답변보기. –

4

File::Tee는 당신이 필요로하는 기능을 제공합니다.

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

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 
관련 문제