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

i am using a perl script in which i call other executables and want to redirect the output , error and warning messages to a file.
what i did was i created a file
$logfile = $EXENAME."out"
open( LOGFILE, ">$logfile" )||die "Can't open $logfile"; now i am running command like

$status=system ( "$Cmd1 > LOGFILE 2>&1" );
$status=system ( "$Cmd2 > LOGFILE 2>&1" );
what i want is when i execute any number of commands , all error messages, warning messages and output messages should be redirected to LOGFILE
With the way i am doing, i get a file named as LOGFILE, not the file name which i had created. secondly in LOGFILE i see last command messages.

also is there any way i can use file handle of other perl module like
MODULE::SCRIPT::LOGFILE1 is a file handle in other module and its not closed . can i use it in this module
  • Comment on redirecting output and warning messages

Replies are listed 'Best First'.
Re: redirecting output and warning messages
by salva (Canon) on Mar 20, 2006 at 14:50 UTC
    instead of using the shell to set up the redirections do it yourself from perl:
    sub my_system { my @cmd = @_; my $pid = fork; defined $pid or die "couldn't fork"; if (!$pid) { open STDOUT, '>>&', \*LOGFILE or exit(1); open STDERR, '>>&', \*LOGFILE or exit(1); exec @cmd1; exit(1); } waitpid($pid, 0); return $? == 0; } my $status1 = my_system($cmd1, @args1); my $status2 = my_system($cmd2, @args2);
Re: redirecting output and warning messages
by Fletch (Bishop) on Mar 20, 2006 at 15:01 UTC

    IPC::Run allows this sort of redirection.

Re: redirecting output and warning messages
by QM (Parson) on Mar 20, 2006 at 16:54 UTC
    The other replies have hinted, but neglected to explicitly mention, that you can't use the filehandle in the system argument like that. LOGFILE, the string, gets interpreted by the shell as the name of the file to redirect output to.

    Either use backticks to capture the output in Perl, or replace LOGFILE with $logfile, as in:

    $status=system("$Cmds1 > $logfile 2>&1");
    Note, however, that different shells do this differently. To be portable, do it in Perl yourself.

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

Re: redirecting output and warning messages
by timos (Beadle) on Mar 20, 2006 at 14:46 UTC
    With $foo=`ls` you get the output of ls (STDOUT) into the variable $foo directly, from there you can write it to whereever you want.