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 :)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.