The other answers are better, but here's a
unixy "no modules" solution just for the heck of it:
# Usage: $teed_fh = tee @output_handles;
# Returns a new filehandle that, when written, copies to all @output_h
+andles
sub tee {
use vars qw(*__TEE_FH);
my $tfh = do { \local *__TEE_FH }; # XXX Should use IO::Handle ins
+tead
defined( my $pid = open($tfh, "|-") ) or die "fork: $!";
return select((select($tfh), $| = 1)[0]) if $pid;
for (@_) { select($_); $| = 1 }
while( sysread(STDIN, my $block, 8192) ) { print $_ $block for @_
+}
kill 9,$$ or exit; # XXX Should use POSIX::_exit instead
}
and an example using it to do what you wanted:
# Tee STDOUT to a log file
use vars qw(*LOG);
open LOG, ">>log.txt" or die "log.txt: $!";
*STDOUT = tee(*STDOUT, *LOG);
END { close STDOUT and wait }
# Now do something that writes to STDOUT
print "Hello, world #$_!\n" for (1..20);
# XXX But, should have just used IO::Tee in first place :)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.