how to get text via backticks or system in Perl
Question
I want to call a EXE file in Perl which performs some action
I tried calling the exe file via backtick
and system
but in both the cases i get only the return value
The exe file prints some text on to the console. Is it possible to capture that as well?
I looked into this variable ${^CHILD_ERROR_NATIVE}
but I get only the return value and not text
I am using Perl 5.14
Thanks in advance
La solution
The application might not print its output to STDOUT
but STDERR
instead, which isn't captured by the backtick operator. To capture both, you could use the following:
my $binary = 'foo.exe';
my $output = `$binary 2>&1`;
For a more fine-tuned capturing, you might want to resort to IPC::Open3
with which you can "control" all of a process' streams (IN
, OUT
and ERR
).
Autres conseils
I used to execute commands from perl script and capture the output this way
sub execute_command() {
my($host) = @_;
open(COMMAND_IN, "your_command |");
while (<COMMAND_IN>)
{ #The COMMAND_IN will have the output of the command
#Read the output of your command here...
$ans = $_;
}
close(COMMAND_IN);
return $ans;
}
Check whether it helps you
I recommend the capture
and capture_err
functions from Scriptalicious.
use Scriptalicious qw(capture);
my $output = capture('my_command', 'arg');