IO::Teeのマルチプレックス(多重化)について調べてみた
続・はじめてのPerlの 8.4.4でIO::Teeが紹介されてるが、
サンプルコードの動作とコメントが一致していないような気がしたので、調べてみた。
# 続・はじめてのPerl P104 の擬似コード use IO::Tee $tee_fh = IO::Tee->new( $read_fh, $log_fh, $scalar_fh ); # $read_fh からの読み出し my $message = <$tee_fh>; # $log_fh と $scalar_fh への書き込み print $tee_fh $message;
このままでは、動かないので以下のように修正
use strict; use warnings; use IO::File; use IO::Scalar; use IO::Tee; my $read_fh = IO::File->new( 'read.txt', 'r' ); my $log_fh = IO::File->new( 'log.txt', 'w' ); my $string = ''; my $scalar_fh = IO::Scalar->new( \$string ); my $tee_fh = IO::Tee->new( $read_fh, $log_fh, $scalar_fh ); # $read_fh からの読み出し my $message = <$tee_fh>; print "read line: $message"; # $log_fh と $scalar_fh への書き込み print $tee_fh $message; print $string;
コメントの内容から、入力と出力は別々に行う必要があるのだと思っていた。
だが、実際は違っていた。
実行すると以下のような標準出力が得られる。
$ perl sample.pl read line: aaa aaa aaa
どうやら、入力を行うと同時に出力も行われる模様。
IO::Teeのドキュメントを見てみる。
When read from, the IO::Tee object reads from the input handle given as the first argument to the IO::Tee constructor, then writes any data read to the output handles given as the remaining arguments to the constructor.
IO::Tee - search.cpan.org
自信ないけど、訳するとこんな感じか?
IO::Teeオブジェクトは、IO::Teeコンストラクタの第一引数に与えた入力ハンドルから読み込むとき、コンストラクタの残りの引数に与えた出力ハンドルに、読み取ったすべてのデータを書き込む。
ドキュメントのExampleを実行してみると、やはり読み取りと同時に書き込みが行われてりるようだ。
結論
IO::Teeにおいて、入力と出力の多重化を行った場合は、読み込みと同時に出力も行われる。
というより、サンプルのコメントが分かりにくいだけ?