Best way to capture output from system command to a text file?

int80h picture int80h · Oct 17, 2011 · Viewed 39.2k times · Source

I’m trying to capture output from using Perl’s system function to execute and redirect a system command’s ouptut to a file, but for some reason I’m not getting the whole output.

I’m using the following method:

system("example.exe >output.txt");

What’s wrong with this code, or is there an alternative way of doing the same thing?

Answer

Joel Berger picture Joel Berger · Oct 18, 2011

Same as MVS's answer, but modern and safe.

use strict;
use warnings;

open (my $file, '>', 'output.txt') or die "Could not open file: $!";
my $output = `example.exe`; 
die "$!" if $?; 
print $file $output;

easier

use strict;
use warnings;

use autodie;

open (my $file, '>', 'output.txt');
print $file `example.exe`;

if you need both STDOUT and STDERR

use strict;
use warnings;

use autodie;
use Capture::Tiny 'capture_merged';

open (my $file, '>', 'output.txt');
print $file capture_merged { system('example.exe') };