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

I am a program which is called using system command. I want to send the output from this into a file. Is there a way to do this.

Thanks,
Sid
  • Comment on How to send the Output from system command into a file

Replies are listed 'Best First'.
Re: How to send the Output from system command into a file
by jettero (Monsignor) on Dec 17, 2008 at 16:33 UTC
    Mostly people would do this with the shell, but if you want to write it by hand, it probably looks something like this.
    open my $cmd, "-|", qw(ls -al) or die $!; open my $file, ">", "filename" or die $!; while(<$cmd>) { print $file $_ }

    If you're interested in stdout as well as stderr, IPC::System::Simple might have a role to play.

    -Paul

Re: How to send the Output from system command into a file
by Bloodnok (Vicar) on Dec 17, 2008 at 16:39 UTC
    You don't say how you want the redirection to take place but, assuming you want to keep the use of the system command, you will have to use the shell to do it since system only returns an error code & signal resulting from the call e.g. system("cmd > file");

    A user level that continues to overstate my experience :-))
Re: How to send the Output from system command into a file
by mr_mischief (Monsignor) on Dec 17, 2008 at 16:45 UTC
    TIMTOWTDI.

    my $output = qx{ls}; ( open my $file, '>', 'filename' ) or die "Cannot open file 'filename' + for writing: $!\n"; print $file $output; close $file or die "Error writing to file 'filename': $!\n";

    See perlop for information about qx and other quote-like operators.