STDOUT
Perlスクリプト内でストリームを2つのファイル(複製)にリダイレクトするにはどうすればよいですか?現在、私は単一のログファイルにストリーミングしています。
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!
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
File::Teeは必要な機能を提供します。
use File::Tee qw( tee );
tee(STDOUT, '>', 'stdout.txt');
Unix ライクなシステムを使用している場合は、teeユーティリティを使用してください。
$ perl -le 'print "Hello, world"' | ティー /tmp/foo /tmp/bar こんにちは世界 $ 猫 /tmp/foo /tmp/bar こんにちは世界 こんにちは世界
プログラム内からこの複製を設定する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-copys-demo こんにちは世界! $ 猫 /tmp/foo /tmp/bar こんにちは世界! こんにちは世界!