http://www.perlmonks.org?node_id=839949

nagalenoj has asked for the wisdom of the Perl Monks concerning the following question:

How could I write the same content in 2(or more) handles? I've a script where I want to write the same content to a file handle and a socket.

some thing like., print <more than one file handle> "Hello world";

what is the way to go?

Replies are listed 'Best First'.
Re: writing in 2 handles
by Corion (Patriarch) on May 14, 2010 at 07:06 UTC
Re: writing in 2 handles
by cdarke (Prior) on May 14, 2010 at 08:27 UTC
    # Create an array of file handles my @fhs; for my $file (qw (gash1.txt gasg2.txt gash3.txt) { open (my $fh, '>', $file) or die "Unable to open $file: $!"; push @fhs, $fh } # Now for the print print $_ "Some stuff\n" for @fhs; print $_ "Some more stuff\n" for @fhs; # Close the files close $_ for @fhs;
Re: writing in 2 handles
by ambrus (Abbot) on May 14, 2010 at 10:20 UTC

    I usually use a subroutine similar to this,

    open LOG, ">>", "/path/to/logfile" or die; sub logme { print STDERR @_; print LOG @_; } logme "something interesting happened\n";
Re: writing in 2 handles
by Marshall (Canon) on May 16, 2010 at 22:02 UTC
    For the Windows challenged: This will do pretty much all that is to be done. *inx has a standard tee function.
    # tee program # quick tool by Marshall 7/2007 use strict; use warnings; sub usage () { print "TEE USAGE:\n tees stdout to a file and to stdout\n". " program | tee outfile\n". " sends stdout from program to outfile\n"; exit; } my $filename = shift @ARGV; usage unless $filename; open (OUTFILE, ">$filename") or (die "Can't open OUTFILE: $!"); while (<>) { print; print OUTFILE; } close OUTFILE; 1; Adapt to your needs, re: different FILEHANDLES or use IO::Tee