How to properly capture the return value of a unix command?
perl, return-value, shell
Solution
Variables are interpolated inside backticks, so the `$?` in
my $pstate=`nc -z 8.8.8.8 441; echo $?`
refers to Perl's `$?`, not the shell's `$?`. And what the shell sees is something like
nc -z 8.8.8.8 441 ; echo 0
To fix this, you can escape the shell command
my $pstate=`nc -z 8.8.8.8 441; echo \$?`;
or use the `qx` operator with the single quote as a separator (this is the one exception to the "interpolation inside the `qx` operator" rule)
my $pstate=qx'nc -z 8.8.8.8 441; echo $?';
or use `readpipe` with a non-interpolated quote construction
my $pstate= readpipe( 'nc -z 8.8.8.8 441; echo $?' );
my $pstate= readpipe( q{nc -z 8.8.8.8 441; echo $?} );
Problem
I'm having trouble getting the return value of a unix command into a perl variable. Unix command: ``` #nc -z 8.8.8.8 441; echo $? 1 ``` Perl command: ``` #perl -e 'my $pstate=`nc -z 8.8.8.8 441; echo $?`; print $pstate;' 0 ``` So the perl command seems to get a return value of "no error"? How can I properly capture the return value of the *nix command? Another instance: ``` #perl -e 'my $pstate=`ping -v 8.8.8.8 -c 1`; print $pstate;' PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. ``` This returns the proper value. So what am I doing wrong in the first instance?