atu has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, i have a question: I have a perl script that is calling many other scripts. My perl code is something like that:

lots of things here ..... system ("aPerlScript.pl 1 2"); .....
At this point aPerlScript.pl starts with inputs 1 and 2, does a lot of stuff, and it again prints a lot of stuff on the screen. Now i want to have them on the screen but i also want to have them on a log file. if i use:
my $output = `aPerlScript.pl 1 2`; print "$output \n"; logToSomeFile "$output"; #this is a sub routine that prints to file.
i can get them on screen and file but it is delayed a lot. aPerlScript.pl keeps running for 3-4 minutes, and lets say prints 100 rows on screen every now and then. if i use backticks to capture it, script seems to stuck during that duration, doing nothing at all, and once aPerlScript.pl completes its work, i suddenly get 3982498234 rows show on display. How can i solve that problem? TL;DR: How can i get the same output of a script that is called from another script on both screen and a log file simultaniosly?

Replies are listed 'Best First'.
Re: script and its output on different handles
by choroba (Cardinal) on Nov 28, 2013 at 10:39 UTC
    Not tested:
    open my $SCRIPT, 'aPerlScript.pl 1 2 |' or die $!; while (<$SCRIPT>) { print; log($logfile, $_); }
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: script and its output on different handles
by hdb (Monsignor) on Nov 28, 2013 at 10:39 UTC

    At least on Unix, there is a utility called tee which helps you to print to the screen and to a file simultaneously.

Re: script and its output on different handles
by drmrgd (Beadle) on Nov 28, 2013 at 13:03 UTC
    I've used IO::Tee to do this kind of thing in the past. In short, you use the module to create a file handle pointing to your log file and STDOUT kind of like this:
    use warnings; use strict; use IO::Tee; open( my $log_fh, ">>", "mylog.txt" ) || die "Can't open the log for w +riting: $!"; my $output = IO::Tee->new( \*STDOUT, $log_fh ); print $output "Starting the script...\n";
    That should print 'Starting the script...' to both the logfile and the screen. Also, since you now have a couple file handles at your disposal, you can just print to the screen or just print to '$log_fh' at will if you like.