Jerry Jerry - 3 years ago 197
Perl Question

Get both STDOUT and STDERR of a program or script to a variable in perl

I did lot of google to redirect the both STDOUT and STDERR of a program to a variable in perl, Initially i tried using both open and backticks, but failed to capture Error signal to the variable.

I am posting this question because Now I got the solution and hope it may helps others..

Answer Source

To get both STDOUT and STDERR into a variable use following code snippet using backticks (``).

When wrong command provided,

my $Temp_return;
$Temp_return = `lse 2>&1`;
print "return = " . $Temp_return . "\n";

Error OutPut is,

return = 'lse' is not recognized as an internal or external command, operable program or batch file.

For correct command you will get the result accordingly.

As an additional information different methods for executing the command in Perl are.

system() : If you want to execute a command and not interested in reading console output of the executed command.

exec : When you don't want to return to the calling Perl script. use same.

backticks : When you want to store /read the console output of the command into a Perl variable. Initial I mistakenly thought, required to use Single cores('') instead, for backticks (``) and get confused, because its almost similar to Single cores(''), please give attention.

open() : When you want to pipe the command (as input or output) to your script.

Hope it could be helpful for you..... :)

BR, Jerry James

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download