Perl语言再学习(4): 子程序执行

perl的系统命令/外部子程序调用方法

大致说来是以下几种

exec函数

用法:

exec LIST
exec PROGRAM LIST

特征:

system函数

用法:

system LIST
system PROGRAM LIST

特征:

当然,也可以用下面代码检查程序的返回状态

if ($? == 1) {
   print "failed to execute: $!\n";
}
elsif ($? & 127) {
   printf "child died with signal %d, %s coredump\n",
	   ($? & 127),  ($? & 128) ? 'with' : 'without';
}
else {
   printf "child exited with value %d\n", $? >> 8;
}

`` (反引号,backticks)

用法:

`LIST`
`PROGRAM LIST`

特征:

IPC::Open2 IPC::Open3

用法:

use IPC::Open2;
$pid = open2(\*CHLD_OUT, \*CHLD_IN, 'some cmd and args');

# or without using the shell
$pid = open2(\*CHLD_OUT, \*CHLD_IN, 'some', 'cmd', 'and', 'args');

# or with handle autovivification
my($chld_out, $chld_in);
$pid = open2($chld_out, $chld_in, 'some cmd and args');

# or without using the shell
$pid = open2($chld_out, $chld_in, 'some', 'cmd', 'and', 'args');
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;

特征:

附注:

为了防止丢失输出一般用IO::Handle中的autoflush()函数刷新缓冲区。 或者设定autoflush参数 $| = 1;