我正在使用perl的system
函数,但我对此函数的返回值感到困惑。请考虑以下示例:
[wakatana@arch ~]$ grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
[wakatana@arch ~]$ echo $?
0
[wakatana@arch ~]$ grep roots /etc/passwd
[wakatana@arch ~]$ echo $?
1
[wakatana@arch ~]$ perl -e 'my $code = system("grep root /etc/passwd 2>&1 1>/dev/null"); print $code . "\n"'
0
[wakatana@arch ~]$ perl -e 'my $code = system("grep roots /etc/passwd 2>&1 1>/dev/null"); print $code . "\n"'
256
为什么第二个perl返回256而不是1?
以下摘自perldoc:
“返回值-1表示无法启动程序或wait(2)系统调用错误(检查$!,原因)”
在执行外部命令时似乎出现了问题,所以我也尝试按照命令来弄清楚发生了什么,但我仍然迷失了。
# Seems that regular bash command, in this case exit, is equivalent to blablabla
[wakatana@arch ~]$ perl -e 'my $code = system("exit 2"); print $code . "\n"'
-1
[wakatana@arch ~]$ perl -e 'my $code = system(blablabla); print $code . "\n"'
-1
[wakatana@arch ~]$ perl -e 'my $code = system("grep roots /etc/passwd 2>&1 1>/dev/null") or die $!'
[wakatana@arch ~]$
请有人解释一下这种行为。
@EDIT 回复:Paul Roub和ikegami
神秘解决了:
2[wakatana@arch ~]$ perl -e 'my $code = system("bash -c \"exit 2\""); print $code >> 8; print "\n"'
2
[wakatana@arch ~]$ perl -e 'my $code = system("exit 2"); print $! . "\n"'
No such file or directory
[wakatana@arch ~]$ perl -e 'my $code = system(blablabla); print $! . "\n"'
No such file or directory
[wakatana@arch ~]$ perl -e 'my $code = system("grep roots /etc/passwd 2>&1 1>/dev/null"); print $code >> 8; print "\n"'
1