Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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?

Replies are listed 'Best First'.
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 (Abbot) 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://839949]
Approved by Hue-Bond
[karlgoethebier]: before i forget it: good morning

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2018-01-20 09:32 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (226 votes). Check out past polls.