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 \□ 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, |
|
|---|