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?
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') };