Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Perl output on console as well as on text file

by Athanasius (Archbishop)
on Jan 05, 2015 at 07:03 UTC ( [id://1112152]=note: print w/replies, xml ) Need Help??


in reply to Perl output on console as well as on text file

Hello shyamasoni,

If you don’t need the text file to be written out until the script has completed, you can use either the tee_stdout or the tee_merged function from Capture::Tiny. Here is some proof-of-concept code:

#! perl use strict; use warnings; use Capture::Tiny 'tee_merged'; my $outfile = 'sqr.txt'; my $stdout = tee_merged \&square; open(my $fh, '>', $outfile) or die "Cannot open file '$outfile' for writing: $!"; print $fh $stdout; close $fh or die "Cannot close file '$outfile': $!"; sub square { print "Enter a number (0 to quit): "; my $n = <STDIN>; chomp $n; while ($n) { printf "%f squared is %f\n", $n, $n * $n; print "Enter a number (0 to quit): "; $n = <STDIN>; chomp $n; } print "Bye!\n"; }

Console output:

16:51 >perl 1112_SoPW.pl Enter a number (0 to quit): 57.6 57.600000 squared is 3317.760000 Enter a number (0 to quit): .00211 0.002110 squared is 0.000004 Enter a number (0 to quit): 12 12.000000 squared is 144.000000 Enter a number (0 to quit): 0 Bye! 16:52 >

Text file output:

Enter a number (0 to quit): 57.600000 squared is 3317.760000 Enter a number (0 to quit): 0.002110 squared is 0.000004 Enter a number (0 to quit): 12.000000 squared is 144.000000 Enter a number (0 to quit): Bye!

Note that tee_merged captures output to STDOUT and STDERR, but not input from STDIN (i.e. via the keyboard).

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://1112152]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2024-04-26 00:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found