CUFP
jdporter
snippet
<div class="Description">This module encapsulates any number of filehandles in a kind of "meta-filehandle". Any operations you perform on the meta-filehandle are delegated to <i>all</i> of the contained handles. This may be similar to the [mod://IO::Tee] module.<p>
This solution was developed in response to [id://214143].
<p>
<b>Updated</b> in response to helpful comments from [jmcnamara] and [Aristotle].</div>
<CODE>
=head1 NAME
IO::MultiHandle - Encapsulate multiple handles in one.
=head1 SYNOPSIS
use IO::MultiHandle;
my $logfh = IO::File->new( "> $outfile" ) or die "write $outfile: $!";
# create a multi-handle which will write to both
# STDERR and the filehandle created above:
my $mfh = new IO::MultiHandle *STDERR, $logfh;
print $mfh "A line of output.\n";
=cut
</code>
<code>
package Tie::MultiHandle; # do not use directly.
use IO::Handle;
sub TIEHANDLE
{
my $pkg = shift;
bless [ @_ ], $pkg
}
sub AUTOLOAD
{
my( $self, @args ) = @_;
our( $AUTOLOAD );
$AUTOLOAD =~ s/.*::(.*)/\L$1/;
for my $fh ( @$self ) { $fh->$AUTOLOAD( @args ); }
}
sub DESTROY
{
}
package IO::MultiHandle;
use Symbol;
# takes a list of handles
sub new
{
my $pkg = shift;
my $self = gensym;
tie *$self, Tie::MultiHandle::, @_;
bless $self, $pkg
}
</CODE>