Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Split output to STDOUT as well as a file

by Athanasius (Archbishop)
on Jan 05, 2016 at 06:34 UTC ( [id://1151915]=note: print w/replies, xml ) Need Help??


in reply to Split output to STDOUT as well as a file

Hello razmeth, and welcome to the Monastery!

The IO::Tee module recommended by BrowserUk is likely the best fit for your stated requirements. But if you need something fancier, consider Tie::STDOUT:

#! perl use strict; use warnings; my $file = 'test.txt'; open(my $fh, '>', $file) or die "Cannot open file '$file' for writing: $!"; use Tie::STDOUT print => sub { print @_; print $fh '[', scalar localtime, ']: ', @_; }, printf => sub { printf @_; print $fh '[', scalar localtime, ']: '; printf $fh @_; }; print "Perl is cool!\n"; printf "Pi is %f\n", atan2(1, 1) * 4; close $fh or die "Cannot close file '$file': $!";

Output:

16:32 >perl 1504_SoPW.pl Perl is cool! Pi is 3.141593 16:32 >

Contents of file “test.txt”:

[Tue Jan 5 16:32:03 2016]: Perl is cool! [Tue Jan 5 16:32:03 2016]: Pi is 3.141593

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1151915]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2024-04-19 14:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found