http://www.perlmonks.org?node_id=956117


in reply to Incorrect value 0 reported in command execution return value variable $?, when trying with expect->send command

Insert this line and the solution will reveal before your weary eyes...

print "$command ; echo COMMAND_RET:$? | sed 's/^/COMMAND_OUT: /g'; ech +o -n END_; echo EXPECT\n";
Hint: You need to escape $?.

Why not get rid of the sed-invocation?

$exp->send("$command ; echo 'COMMAND_OUT: COMMAND_RET:'\$?; echo END_E +XPECT\n");
Depending on the shells flavour of echo, you could also get rid of the second echo invocation.