The failure message is printed to STDERR
, while backticks return only what goes to STDOUT
.
You can redirect the STDERR
stream to the STDOUT
stream
$result = `echo exit | telnet 127.0.0.1 9443 2>&1`;
See I/O redirection.
There are more rounded ways to do this, using various forms of open
. See it in perlfaq8. There are also various modules for this. The Capture::Tiny makes it rather easy.
use warnings 'all';
use strict;
use Capture::Tiny qw(capture);
my $cmd = 'echo exit | telnet 127.0.0.1 9443';
my ($stdout, $stderr) = capture {
system ( $cmd );
};
print "STDOUT: $stdout";
print "STDERR: $stderr";
This prints for me
STDOUT: Trying 127.0.0.1...
STDERR: telnet: connect to address 127.0.0.1: Connection refused
The module has many more capabilities. From the docs
Capture::Tiny provides a simple, portable way to capture almost anything sent to STDOUT or STDERR, regardless of whether it comes from Perl, from XS code or from an external program.