This question already has an answer here:
-
How can I get the CPU time for a perl system call?
3 answers
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..
To get both STDOUT and STDERR into a variable use following code snippet using backticks (``).
Make sure 2>&1 is places at the end of your command, to redirect STDERR in to STDOUT.
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