in reply to Capturing STDOUT and STDERR of system command, with pure perl?

If you want to return a variable containing the contents of the last issued command rather than have it print to the screen you could do something like... #use diagnostics; use strict; use warnings; sub SafeSystem { (my $command, my $error) = @_; # Run the command, redirect standard and error output to log file my $result = system($command . " 1>C:/output 2>&1"); # Read the output open(SYS_OUT, "C:/output") or die "SafeSystem couldn't open C:/output"; my $output = join "", <SYS_OUT>; close SYS_OUT; # Did the command succeed? if ($result ne 0) or die; return $output; } # RUN A COMMAND BUT PRINT THE OUTPUT TO A VARIABLE RATHER THAN STDOUT my $thecmd = "ping www.google.com"; my $res = SafeSystem($thecmd, "Error");
  • Comment on Re: Capturing STDOUT and STDERR of system command, with pure perl?

Replies are listed 'Best First'.
Re^2: Capturing STDOUT and STDERR of system command, with pure perl?
by Anonymous Monk on Jan 21, 2009 at 08:56 UTC
    Simplified to this...

    # To get the numerical result (in most cases, the error code) of the command use the $res variable...
    my $thecmd = "dir";
    my $res = system("$thecmd . " 1>C:/output 2>1");
    print $res;


    # To get the string output result of the command, just look at the file in C:/output...
    open(SYS_OUT, "C:/output") or die "Could not open the output";
    my $output = join "", <SYS_OUT>;
    close SYS_OUT;
    print $output;