Beefy Boxes and Bandwidth Generously Provided by pair Networks httptech
Do you know where your variables are?
 
PerlMonks  

writing in 2 handles

by nagalenoj (Friar)
on May 14, 2010 at 06:53 UTC ( #839949=perlquestion: print w/ replies, xml ) Need Help??
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?

Comment on writing in 2 handles
Re: writing in 2 handles
by Corion (Pope) 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 (Prior) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://839949]
Approved by Hue-Bond
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2014-04-19 21:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (483 votes), past polls