in reply to How to print STDOUT to a file

system("script.sh >> filename");
if you're on a *NIX. This appends to the file (so doesn't clobber it), if you want to start anew with every call to system use ">" instead of ">>".

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan

Replies are listed 'Best First'.
Re^2: How to print STDOUT to a file
by salva (Canon) on Nov 14, 2005 at 12:08 UTC
    system("script.sh >> filename");
    calls the shell interpreter under the hood, something that can be very inconvenient (and even dangerous). For instance, the script arguments have to be properly quoted or they could be wrongly splitted by the shell

    An alternative way to redirect the output for the called program is to reopen STDOUT:

    open my $oldout, ">&STDOUT" or die "Can't dup STDOUT: $!"; open STDOUT, ">", $fn or die "Can't open $fn: $!"; system $script, @args; open STDOUT, ">&", $oldout;
    Or on Unix/Linux systems, you can use fork and exec instead of system and perform the redirection after the fork:
    my $pid = fork; if (defined $pid and $pid == 0) { open STDOUT, ">", $fn or die; exec $script, @args; exit 1; }
      Works fine. Thank you very much.